Anonymous user
Knapsack problem/Continuous: Difference between revisions
→{{header|Ada}}: Slightly edited the formatting of output; Added the requested output
(→{{header|C++}}: Added output the lack of which had been previously flagged up.) |
(→{{header|Ada}}: Slightly edited the formatting of output; Added the requested output) |
||
Line 53:
=={{header|Ada}}==
<lang Ada>with Ada.Text_IO;
with Ada.Float_Text_IO;
with Ada.Strings.Unbounded;
procedure Knapsack_Continuous is
package US renames Ada.Strings.Unbounded;
type Item is record
Name : US.Unbounded_String;
Line 66:
Taken : Float;
end record;
function "<" (Left, Right : Item) return Boolean is
begin
Line 72:
Float (Right.Value) / Right.Weight;
end "<";
type Item_Array is array (Positive range <>) of Item;
function Total_Weight (Items : Item_Array) return Float is
Sum : Float := 0.0;
begin
for I in Items'Range loop
Sum := Sum +
end loop;
return Sum;
end Total_Weight;
function Total_Value (Items : Item_Array) return Float is
Sum : Float := 0.0;
begin
for I in Items'Range loop
Sum := Sum + Float (Items (I).Value) / Items(I).Weight * Items (I).Taken;
end loop;
return Sum;
end Total_Value;
procedure Solve_Knapsack_Continuous
(Items : in out Item_Array;
Line 127:
end;
end Solve_Knapsack_Continuous;
All_Items : Item_Array :=▼
▲ All_Items : Item_Array :=
((US.To_Unbounded_String ("beef"), 3.8, 36, 0.0),
(US.To_Unbounded_String ("pork"), 5.4, 43, 0.0),
Line 138 ⟶ 137:
(US.To_Unbounded_String ("salami"), 3.0, 95, 0.0),
(US.To_Unbounded_String ("sausage"), 5.9, 98, 0.0));
begin
Solve_Knapsack_Continuous (All_Items, 15.0);
Ada.Text_IO.
Ada.Text_IO.
Ada.Float_Text_IO.Put (Total_Value (All_Items), 0, 2, 0);
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line ("Items:");
for I in All_Items'Range loop
if All_Items (I).Taken > 0.0 then
Ada.Text_IO.
Ada.Text_IO.Put_Line (" of
end if;
end loop;
end Knapsack_Continuous;
</lang>
{{out}}
<pre>
Total Weight: 15.00
Total Value: 349.38
Items:
3.00 of salami
3.60 of ham
2.50 of brawn
2.40 of greaves
3.50 of welt
</pre>
=={{header|GNU APL}}==
|