Knapsack problem/Continuous: Difference between revisions

Content added Content deleted
(added Pascal example)
(→‎{{header|Pascal}}: simplified version)
Line 2,620: Line 2,620:
constructor Make(const n: string; w, v: Double);
constructor Make(const n: string; w, v: Double);
end;
end;

TSelItem = record
Name: string;
Weight: Double;
end;

THaul = array of TSelItem;


constructor TItem.Make(const n: string; w, v: Double);
constructor TItem.Make(const n: string; w, v: Double);
Line 2,640: Line 2,633:
Result := CompareValue(R.Price, L.Price);
Result := CompareValue(R.Price, L.Price);
end;
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
var
Items: array of TItem;
Items: array of TItem;
I: TSelItem;
MaxWeight: Double;
I: Integer;

begin
begin
Items := [
Items := [
Line 2,676: Line 2,650:
TItem.Make('sausage', 5.9, 98)
TItem.Make('sausage', 5.9, 98)
];
];
TArrayHelper<TItem>.Sort(Items, 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
Items[I].Weight := Min(Items[I].Weight, MaxWeight);
MaxWeight := MaxWeight - Items[I].Weight;
WriteLn(Items[I].Name, #9, FormatFloat('0.0 kg', Items[I].Weight));
Inc(I);
until (MaxWeight <= 0)or(I = Length(Items));
end.
end.
</syntaxhighlight>
</syntaxhighlight>