Knapsack problem/Continuous: Difference between revisions

→‎{{header|Pascal}}: simplified version
(added Pascal example)
(→‎{{header|Pascal}}: simplified version)
Line 2,620:
constructor Make(const n: string; w, v: Double);
end;
 
TSelItem = record
Name: string;
Weight: Double;
end;
 
THaul = array of TSelItem;
 
constructor TItem.Make(const n: string; w, v: Double);
Line 2,640 ⟶ 2,633:
Result := CompareValue(R.Price, L.Price);
end;
 
function Solve(var aItems: array of TItem; aMaxWeight: Double): THaul;
var
I: Integer = 0;
begin
if Length(aItems) = 0 then exit(nil);
TArrayHelper<TItem>.Sort(aItems, TComparer<TItem>.Construct(ItemCmp));
SetLength(Result, Length(aItems));
repeat
Result[I].Name := aItems[I].Name;
Result[I].Weight := Min(aItems[I].Weight, aMaxWeight);
aMaxWeight := aMaxWeight - Result[I].Weight;
Inc(I);
until (aMaxWeight <= 0)or(I = Length(aItems));
SetLength(Result, I);
end;
 
const
MAX_WEIGHT = Double(15);
 
var
Items: array of TItem;
IMaxWeight: TSelItemDouble;
I: Integer = 0;
 
begin
Items := [
Line 2,676 ⟶ 2,650:
TItem.Make('sausage', 5.9, 98)
];
TArrayHelper<TItem>.Sort(aItemsItems, TComparer<TItem>.Construct(ItemCmp));
for I in Solve(Items, MAX_WEIGHT) do
MaxWeight := 15.0;
WriteLn(I.Name, #9, FormatFloat('0.0 kg', I.Weight));
I := 0;
repeat
ResultItems[I].Weight := Min(aItemsItems[I].Weight, aMaxWeightMaxWeight);
aMaxWeightMaxWeight := aMaxWeightMaxWeight - ResultItems[I].Weight;
WriteLn(Items[I].Name, #9, FormatFloat('0.0 kg', Items[I].Weight));
Inc(I);
until (aMaxWeightMaxWeight <= 0)or(I = Length(aItemsItems));
end.
</syntaxhighlight>
73

edits