Knapsack problem/Unbounded: Difference between revisions

Undo revision 263806 by Cloudius (talk)Roll back all but Scala updates for reason given in last rollback
(Whole Scala contribution erased without a reason.)
(Undo revision 263806 by Cloudius (talk)Roll back all but Scala updates for reason given in last rollback)
Line 1:
{{task|Classic CS problems and programs}}
 
A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, she or he is allowed to take as much as thehe likedlikes itemsof the following items, so long as it will fit in his knapsack, and he can carry it.
 
The travelerHe knows that he can carry no more than   25   'weights' in total; can be carried  and that the capacity of thehis knapsack is   0.25   'cubic lengths'.
 
Looking just above the bar codes on the items he finds their weights and volumes are found. Be  diggingHe digs out thehis recent copy of a financial paper and gets the value of each item can be get.
<table
<table style="text-align: left; width: 80%;" border="4" cellpadding="2" cellspacing="2"><tr>
<td style="fonttext-weightalign: boldleft;" align="left"width: nowrap="nowrap80%;" valignborder="middle4">Item</td>
cellpadding="2" cellspacing="2"><tr><td
<td style="font-weight: bold;" align="left" nowrap="nowrap" valign="middle">Explanation</td>
<td style="font-weight: bold;" align="rightleft" nowrap="nowrap" valign="middle">Value (each)</td>
<td style="font-weight: bold;" align="right" nowrap="nowrap" valign="middle">weightItem</td><td
<td style="font-weight: bold;" align="rightleft" nowrap="nowrap" valign="middle">Volume (each)</td>
valign="middle">Explanation</td><td
</tr><tr>
<td style="font-weight: bold;" align="left" nowrap="nowrap" valign="middle">panacea (vials of)</td>
<td align="left" nowrap="nowrap" valign="middle">IncredibleValue healing properties(each)</td><td
<td align style="leftfont-weight: bold;" align="rightleft" nowrap="nowrap" valign="middle">3000</td>
<td align="left" align="right" nowrap="nowrap" valign="middle">0.3weight</td><td
<td align style="leftfont-weight: bold;" align="rightleft" nowrap="nowrap" valign="middle">0.025</td>
valign="middle">Volume (each)</td></tr><tr><td
</tr><tr>
<td align="left" nowrap="nowrap" valign="middle">ichor (ampules of)</td>panacea
(vials of)</td><td align="left" nowrap="nowrap" valign="middle">Vampires blood</td>
<td align="left" align="right" nowrap="nowrap" valign="middle">1800Incredible healing properties</td><td
<td align="left" align="right" nowrap="nowrap" valign="middle">0.23000</td><td
<td align="left" align="right" nowrap="nowrap" valign="middle">0.0153</td><td
align="left" nowrap="nowrap" valign="middle">0.025</td></tr><tr><td
</tr><tr>
<td align="left" nowrap="nowrap" valign="middle">gold (bars)</td>ichor
(ampules of)</td><td align="left" nowrap="nowrap" valign="middle">Shiney shiney</td>
<td align="left" align="right" nowrap="nowrap" valign="middle">2500Vampires blood</td><td align="left"
<td align="left" align="right" nowrap="nowrap" valign="middle">2.01800</td><td
<td align="left" align="right" nowrap="nowrap" valign="middle">0.0022</td><td
align="left" nowrap="nowrap" valign="middle">0.015</td></tr><tr><td
</tr><tr>
<td style="background-color: rgb(255, 204, 255);" align="left" nowrap="nowrap" valign="middle">Knapsack</td>gold
(bars)</td><td style="background-color: rgb(255, 204, 255);" align="left" nowrap="nowrap" valign="middle">For the carrying of</td>
valign="middle">Shiney shiney</td><td align="left"
<td style="background-color: rgb(255, 204, 255);" align="right" nowrap="nowrap" valign="middle">-</td>
<td style="background-color: rgb(255, 204, 255);" align="right" nowrap="nowrap" valign="middle">&lt;=252500</td><td
<td style="background-color: rgb(255, 204, 255);" align="rightleft" nowrap="nowrap" valign="middle">&lt;=2.0.25</td><td
align="left" nowrap="nowrap" valign="middle">0.002</td></tr><tr><td
</tr></table>
style="background-color: rgb(255, 204, 255);" align="left"
nowrap="nowrap" valign="middle">Knapsack</td><td
style="background-color: rgb(255, 204, 255);" align="left"
nowrap="nowrap" valign="middle">For the carrying of</td><td
style="background-color: rgb(255, 204, 255);" align="left"
nowrap="nowrap" valign="middle">-</td><td
style="background-color: rgb(255, 204, 255);" align="left"
nowrap="nowrap" valign="middle">&lt;=25</td><td
style="background-color: rgb(255, 204, 255);" align="left"
nowrap="nowrap" valign="middle">&lt;=0.25&nbsp;</td></tr>
</table>
 
<br>
The travellerHe can only take whole units of any item, but there is much more of any item than everhe could beever carried.carry
 
 
;Task:
Show how many of each item thedoes traveller canhe take to maximize the value of items he is carriedcarrying away with him.
 
 
;Note:
* &nbsp; There are four solutions that maximize the value taken. &nbsp; Only one ''need'' be given.
 
 
<!-- All solutions
 
# ((value, -weight, -volume), (#panacea, #ichor, #gold)
[((54500, -25.0, -0.24699999999999997), (0, 15, 11)),
Line 53 ⟶ 71:
# (9, 0, 11) also minimizes weight and volume within the limits of calculation
-->
 
;Related tasks:
* &nbsp; [[Knapsack problem/Bounded]]
* &nbsp; [[Knapsack problem/Continuous]]
* &nbsp; [[Knapsack problem/0-1]]<br><br>
<br><br>
 
=={{header|360 Assembly}}==
{{trans|Visual Basic}}
Line 258 ⟶ 279:
END KNAPSACK</lang>
{{out}}
<pre>
<pre> Value Weight Volume Panacea Ichor Gold
Value Weight Volume Panacea Ichor Gold
54500 24.7 0.247 9 0 11
54500 24.8 0.247 6 5 11
Line 264 ⟶ 286:
54500 25.0 0.247 0 15 11
</pre>
 
=={{header|Ada}}==
{{output?|Ada|reason}}
{{trans|Python}}
<lang Ada>with Ada.Text_IO;
Line 332 ⟶ 354:
Ada.Text_IO.Put_Line ("Gold: " & Natural'Image (Best_Amounts (3)));
end Knapsack_Unbounded;</lang>
 
=={{header|ALGOL 68}}==
{{trans|Python}}<lang algol68>MODE BOUNTY = STRUCT(STRING name, INT value, weight, volume);
Line 442 ⟶ 465:
name OF items, max items));
printf(($" The weight to carry is "f(d)", and the volume used is "f(d)l$,
weight OF max, volume OF max))</lang>Output:
Output:<pre>The maximum value achievable (by dynamic programming) is +54500
The number of (panacea, ichor, gold) items to achieve this is: ( 9, 0, 11) respectively
The weight to carry is 247, and the volume used is 247</pre>
 
=={{header|AutoHotkey}}==
{{output?|AutoHotkey|reason}}
Brute Force.
<lang AutoHotkey>Item = Panacea,Ichor,Gold
Line 474 ⟶ 497:
}
MsgBox Value = %$%`n`nPanacea`tIchor`tGold`tWeight`tVolume`n%t%</lang>
 
=={{header|Bracmat}}==
<lang bracmat>(knapsack=
Line 546 ⟶ 570:
!knapsack;
</lang>
Output:
Output:<pre>Take 15 items of ichor.
<pre>Take 15 items of ichor.
Finally take 11 items of gold.
The value in the knapsack is 54500.</pre>
 
=={{header|C}}==
 
figures out the best (highest value) set by brute forcing every possible subset.
 
<lang c>#include <stdio.h>
#include <stdlib.h>
Line 610 ⟶ 638:
}
</lang>
 
{{output}}<pre>9 panacea
0 ichor
11 gold
best value: 54500</pre>
</pre>
 
=={{header|C_sharp|C#}}==
<lang csharp>/*Knapsack
Line 670 ⟶ 701:
}
}</lang>
Produces:
Produces:<pre>===Solver Foundation Service Report===
<pre>
===Solver Foundation Service Report===
Date: 28/01/2012 17:18:56
Version: Microsoft Solver Foundation 3.0.1.10599 Express Edition
Line 704 ⟶ 737:
take(Panacea): 9
take(Ichor): 0
take(Gold): 11</pre>
</pre>
 
=={{header|Clojure}}==
<lang lisp>(defstruct item :value :weight :volume)
Line 746 ⟶ 781:
(println "Total volume: " (float v))
(println "Containing: " p "Panacea," i "Ichor," g "Gold")))</lang>
Calling <tt>(print-knapsack (best-by-value (knapsacks)))</tt> would result in something like:<pre>Maximum value: 54500
<pre>Maximum value: 54500
Total weight: 24.7
Total volume: 0.247
Line 759 ⟶ 795:
(print-knapsack k)
(println)))</lang>
Calling <tt>(print-knapsacks (all-best-by-value (knapsacks)))</tt> would result in something like:<pre>Maximum value: 54500.0
<pre>
Maximum value: 54500.0
Total weight: 25.0
Total volume: 0.247
Line 777 ⟶ 815:
Total weight: 24.7
Total volume: 0.247
Containing: 9 Panacea, 0 Ichor, 11 Gold</pre>
</pre>
 
=={{header|Common Lisp}}==
A dynamic programming <i>O(maxVolume &times; maxWeight &times; nItems)</i> solution, where volumes and weights are integral values.
Line 842 ⟶ 882:
250 ; total volume
247) ; total weight</pre>
 
=={{header|D}}==
{{trans|Python}}
Line 899 ⟶ 940:
This is achieved by carrying (one solution) 0 panacea, 15 ichor and 11 gold
The weight to carry is 25.0 and the volume used is 0.247</pre>
 
===Alternative Version===
The output is the same.
Line 927 ⟶ 969:
writefln("The weight to carry is %4.1f and the volume used is %5.3f", best[0][1..$]);
}</lang>
 
=={{header|E}}==
{{output?|E|reason}}
This is a mostly brute-force general solution (the first author of this example does not know dynamic programming); the only optimization is that when considering the last (third) treasure type, it does not bother filling with anything but the maximum amount.
<lang e>pragma.enable("accumulator")
Line 1,010 ⟶ 1,052:
 
printBest(emptyKnapsack, [panacea, ichor, gold])</lang>
 
=={{header|EchoLisp}}==
Use a cache, and multiply by 10^n to get an integer problem.
Line 1,082 ⟶ 1,125:
 
(length (hash-keys H)) ;; # entries in cache
→ 218</lang>
 
</lang>
 
=={{header|Eiffel}}==
<lang Eiffel>
Line 1,166 ⟶ 1,212:
end
 
end</lang>
</lang>
{{out}}
<pre>
<pre>Maximum value achievable is 54500.
Maximum value achievable is 54500.
This is achieved by carrying 0 panacea, 15 ichor and 11 gold.
The weight is 25 and the volume is 0.247.
</pre>
 
=={{header|Elixir}}==
Brute Force:
Line 1,225 ⟶ 1,274:
maximum = Item.new(0.25, 25, 0)
Knapsack.solve_unbounded(items, maximum)</lang>
 
{{out}}
<pre>
<pre>Maximum value achievable is 54500 volume weight value
Maximum value achievable is 54500 volume weight value
[gold: 11, ichor: 0, panacea: 9] => 0.247, 24.7, 54500
[gold: 11, ichor: 5, panacea: 6] => 0.247, 24.8, 54500
Line 1,232 ⟶ 1,283:
[gold: 11, ichor: 15, panacea: 0] => 0.247, 25.0, 54500
</pre>
 
=={{header|Factor}}==
{{output?|Factor|reason}}
This is a brute force solution. It is general enough to be able to provide solutions for any number of different items.
<lang factor>USING: accessors combinators kernel locals math math.order
Line 1,276 ⟶ 1,327:
find-max-amounts [ 1 + iota ] map <product-sequence>
[ <bounty> ] [ max ] map-reduce ;</lang>
 
=={{header|Forth}}==
<lang forth>\ : value ; immediate
Line 1,377 ⟶ 1,429:
The traveller's knapsack contains 0 vials of panacea, 15 ampules of ichor,
11 bars of gold, a total value of 54500. ok
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
Line 1,432 ⟶ 1,485:
This is achieved by carrying 0 panacea, 15 ichor and 11 gold items
The weight to carry is 25.0 and the volume used is 0.247
 
=={{header|Go}}==
Recursive brute-force.
Line 1,500 ⟶ 1,554:
sumCount, sumWeight, sumVolume, sumValue)
}</lang>
 
Output:<pre>Panacea x 9 -> Weight: 2.7 Volume: 0.225 Value: 27000
Output:
<pre>
Panacea x 9 -> Weight: 2.7 Volume: 0.225 Value: 27000
Ichor x 0 -> Weight: 0.0 Volume: 0.000 Value: 0
Gold x 11 -> Weight: 22.0 Volume: 0.022 Value: 27500
TOTAL ( 20 items) Weight: 24.7 Volume: 0.247 Value: 54500
</pre>
 
=={{header|Groovy}}==
Solution: dynamic programming
Line 1,554 ⟶ 1,612:
}
}</lang>
 
Output:<pre> Item Order: [panacea, ichor, gold]
Output:
<pre> Item Order: [panacea, ichor, gold]
Elapsed Time: 26.883 s
 
Line 1,583 ⟶ 1,643:
item: gold (bars) count:11 weight:22.0 Volume:0.022
item: panacea (vials of) count: 9 weight: 2.7 Volume:0.225</pre>
 
While this solver can only be used to detect two of the four possible solutions, the other two may be discovered by noting that 5 ampules of ichor and 3 vials of panacea have the same value and the same volume and only differ by 0.1 in weight. Thus the other two solutions can be derived by substitution as follows:<pre>Total Weight: 24.9
While this solver can only be used to detect two of the four possible solutions, the other two may be discovered by noting that 5 ampules of ichor and 3 vials of panacea have the same value and the same volume and only differ by 0.1 in weight. Thus the other two solutions can be derived by substitution as follows:
<pre>Total Weight: 24.9
Total Volume: 0.247
Total Value: 54500
Line 1,596 ⟶ 1,658:
item: ichor (ampules of) count: 5 weight: 1.0 Volume:0.075
item: panacea (vials of) count: 6 weight: 1.8 Volume:0.150</pre>
 
=={{header|Haskell}}==
This is a brute-force solution: it generates a list of every legal combination of items (<tt>options</tt>) and then finds the option of greatest value.
Line 1,636 ⟶ 1,699:
main = putStr $ showOpt $ best options
where best = maximumBy $ comparing $ dotProduct vals</lang>
 
Output:<pre>panacea: 9
Output:
 
<pre>panacea: 9
ichor: 0
gold: 11
Line 1,642 ⟶ 1,708:
total volume: 0.247
total value: 54500</pre>
 
=={{header|HicEst}}==
<lang hicest>CHARACTER list*1000
Line 1,675 ⟶ 1,742:
value=54500; Panaceas=6; Ichors=5; Golds=11; weight=24.8; volume=0.247;
value=54500; Panaceas=9; Ichors=0; Golds=11; weight=24.7; volume=0.247; </lang>
 
=={{header|J}}==
Brute force solution.
Line 1,695 ⟶ 1,763:
LF
)</lang>
Example output:<pre> KS''
<pre> KS''
panacea: 3
ichor: 10
Line 1,702 ⟶ 1,771:
total volume: 0.247
total value: 54500</pre>
 
=={{header|Java}}==
With recursion for more than 3 items.
Line 1,840 ⟶ 1,910:
 
} // class</lang>
 
output:<pre>Maximum value achievable is: 54500
output:
<pre>Maximum value achievable is: 54500
This is achieved by carrying (one solution): 0 panacea, 15 ichor, 11 gold,
The weight to carry is: 25 and the volume used is: 0,247</pre>
 
=={{header|JavaScript}}==
Brute force.
Line 1,888 ⟶ 1,961:
item = solutions[i];
document.write("(gold: " + item[0] + ", panacea: " + item[1] + ", ichor: " + item[2] + ")<br>");
}
}</lang>
 
output:<pre>maximum value: 54500
output:
<pre>maximum value: 54500
(gold: 11, panacea: 0, ichor: 15)
(gold: 11, panacea: 3, ichor: 10)
(gold: 11, panacea: 6, ichor: 5)
(gold: 11, panacea: 9, ichor: 0)</pre></lang>
 
=={{header|Julia}}==
{{libheader|JuMP}}<lang julia>
Line 1,920 ⟶ 1,996:
println("bars of gold = ", getvalue(bars_of_gold))</lang>
{{output}}
<pre>
<pre>The optimization problem to be solved is:
The optimization problem to be solved is:
Max 3000 vials_of_panacea + 1800 ampules_of_ichor + 2500 bars_of_gold
Subject to
Line 1,932 ⟶ 2,009:
vials of panacea = 9.0
ampules of ichor = 0.0
bars of gold = 11.0</pre>
</pre>
 
=={{header|Kotlin}}==
{{trans|C}}
Recursive brute force approach:
<lang kotlinscala>// version 1.1.2
 
data class Item(val name: String, val value: Double, val weight: Double, val volume: Double)
Line 2,005 ⟶ 2,084:
 
{{out}}
<pre>
<pre>Item Chosen Number Value Weight Volume
Item Chosen Number Value Weight Volume
----------- ------ ----- ------ ------
panacea 9 27000 2.7 0.23
gold 11 27500 22.0 0.02
----------- ------ ----- ------ ------
2 items 20 54500 24.7 0.25</pre>
</pre>
 
=={{header|M4}}==
A brute force solution:
Line 2,047 ⟶ 2,129:
divert
mv best</lang>
Output:
Output:<pre>54500 (0,15,11) (3,10,11) (6,5,11) (9,0,11)</pre>
<pre>54500 (0,15,11) (3,10,11) (6,5,11) (9,0,11)</pre>
 
=={{header|Lua}}==
{{output?|Lua|reason}}
<lang lua>items = { ["panaea"] = { ["value"] = 3000, ["weight"] = 0.3, ["volume"] = 0.025 },
["ichor"] = { ["value"] = 1800, ["weight"] = 0.2, ["volume"] = 0.015 },
Line 2,086 ⟶ 2,169:
print( k, v )
end</lang>
 
=={{header|Mathematica}}==
Brute force algorithm:
Line 2,106 ⟶ 2,190:
p:0 i:15 v:11</lang>
The volume for all of those is the same, the 'best' solution would be the one that has the least weight: that would the first solution.
 
=={{header|Mathprog}}==
<lang mathprog>/*Knapsack
Line 2,137 ⟶ 2,222:
end;</lang>
The solution produced is at [[Knapsack problem/Unbounded/Mathprog]].
 
=={{header|Modula-3}}==
{{trans|Fortran}}
Line 2,187 ⟶ 2,273:
Put("The weight of this carry is " & Real(totalWeight) & " and the volume used is " & Real(totalVolume) & "\n");
END Knapsack.</lang>
Output:
Output:<pre>Maximum value achievable is 54500
<pre>Maximum value achievable is 54500
This is achieved by carrying 0 panacea, 15 ichor and 11 gold items
The weight of this carry is 25 and the volume used is 0.247</pre>
 
=={{header|OCaml}}==
This is a brute-force solution: it generates a list of every legal combination of items and then finds the best results:
Line 2,268 ⟶ 2,356:
 
let () = List.iter print best_results</lang>
 
outputs:<pre>Maximum value: 54500
outputs:
<pre>Maximum value: 54500
Total weight: 24.7
Total volume: 0.247
Line 2,287 ⟶ 2,377:
Total volume: 0.247
Containing: 0 panacea, 15 ichor, 11 gold</pre>
 
=={{header|OOCalc}}==
OpenOffice.org Calc has (several) linear solvers. To solve this task, first copy in the table from the task description, then add the extra columns:
Line 2,306 ⟶ 2,397:
to produce in seconds:
:[[File:Unbounded Knapsack problem result.PNG|center|Table solved]]
 
=={{header|Oz}}==
Using constraint propagation and branch and bound search:
Line 2,334 ⟶ 2,426:
 
If you study the output, you see how the weight and volume equations automagically constrain the domain of the three variables.
Afterwards SearchBest only has to evaluate 38 different combinations to find an optimal solution:<pre>Search:
 
<pre>Search:
0#solution(gold:_{0#134217726} ichor:_{0#134217726} panacea:_{0#134217726})
1#solution(gold:_{0#12} ichor:_{0#125} panacea:_{0#83})
Line 2,379 ⟶ 2,473:
Result:
solution(gold:11 ichor:15 panacea:0)
total value: 54500</pre>
</pre>
 
=={{header|Pascal}}==
With ideas from C, Fortran and Modula-3.
Line 2,436 ⟶ 2,532:
writeln ('The weight of this carry is ', totalWeight:6:3, ' and the volume used is ', totalVolume:6:4);
end.</lang>
Output:<pre>:> ./Knapsack
<pre>:> ./Knapsack
Maximum value achievable is 54500
This is achieved by carrying 0 panacea, 15 ichor and 11 gold items
The weight of this carry is 25.000 and the volume used is 0.2470</pre>
</pre>
 
=={{header|Perl}}==
Dynamic programming solution. Before you ask, no, it's actually slower for the given data set. See the alternate data set.
Line 2,513 ⟶ 2,612:
 
print "\nCache hit: $hits\tmiss: $misses\n";</lang>
 
Output:<pre>Max value 54500, with:
Item Qty Weight Vol Value
Line 2,523 ⟶ 2,623:
Cache hit: 0 miss: 218</pre>
Cache info is not pertinent to this task, just some info.
 
=={{header|Perl 6}}==
{{Works with|rakudo|2016.08}}
Line 2,569 ⟶ 2,670:
say "panacea\tichor\tgold";
.join("\t").say for @solutions;</lang>
'''Output:'''<pre>maximum value is 54500
<pre>maximum value is 54500
possible solutions:
panacea ichor gold
Line 2,576 ⟶ 2,678:
6 5 11
9 0 11</pre>
 
=={{header|Phix}}==
For each goodie, fill yer boots, then (except for the last) recursively try with fewer and fewer.<br>
Line 2,627 ⟶ 2,730:
printf(1," [weight:%g, volume:%g, %d attempts]\n",
{weight,volume,attempts})</lang>
{{out}}
{{out}}<pre>Profit 54500: 9 panacea, 0 ichor, 11 shiney shiney
<pre>
[weight:24.7, volume:0.247, 98 attempts]</pre>
Profit 54500: 9 panacea, 0 ichor, 11 shiney shiney
[weight:24.7, volume:0.247, 98 attempts]
</pre>
You get the same result whatever order the goodies are in, but with a different number of attempts, gold/ichor/panacea being the
highest at 204.
 
=={{header|PicoLisp}}==
Brute force solution
Line 2,657 ⟶ 2,764:
(apply tab X (4 2 8 5 5 7) N "x") ) )
(tab (14 5 5 7) NIL (sum cadr K) (sum caddr K) (sum cadddr K)) )</lang>
Output:
Output:<pre> 15 x ichor 2 15 1800
<pre> 15 x ichor 2 15 1800
11 x gold 20 2 2500
250 247 54500</pre>
 
=={{header|PowerShell}}==
{{works with|PowerShell|3.0}}
Line 2,729 ⟶ 2,838:
6 vials of panacea, 5 ampules of ichor, and 11 bars of gold worth a total of 54500.
9 vials of panacea, 0 ampules of ichor, and 11 bars of gold worth a total of 54500.</pre>
 
=={{header|Prolog}}==
Works with SWI-Prolog and <b>library simplex</b> written by <b>Markus Triska</b>.
Line 2,817 ⟶ 2,927:
Vo2 is Vo1 + Votemp ),
print_results(S, A0, A1, A2, A3, A4, T, TN, Va2, W2, Vo2).</lang>
Output :<pre> ?- knapsack.
<pre> ?- knapsack.
% 145,319 inferences, 0.078 CPU in 0.079 seconds (99% CPU, 1860083 Lips)
Nb Items Value Weigth Volume
Line 2,824 ⟶ 2,935:
54500 25.00 0.247
true </pre>
 
=={{header|PureBasic}}==
{{trans|Fortran}}
Line 2,916 ⟶ 3,028:
Press Enter to quit</tt>
 
=={{header|Python}}==
See [[Knapsack Problem/Python]]
 
=={{header|R}}==
Brute force method
Line 2,947 ⟶ 3,061:
2171 3 10 11
2223 0 15 11
 
 
Using Dynamic Programming
 
<lang r>Data_<-structure(list(item = c("Panacea", "Ichor", "Gold"), value = c(3000,
<lang r>
Data_<-structure(list(item = c("Panacea", "Ichor", "Gold"), value = c(3000,
1800, 2500), weight = c(3, 2, 20), volume = c(25, 15, 2)), .Names = c("item",
"value", "weight", "volume"), row.names = c(NA, 3L), class = "data.frame")
Line 3,036 ⟶ 3,153:
}
 
main_knapsack(Data_, 250, 250)</lang>
</lang>
<lang r>
Output:
Line 3,043 ⟶ 3,161:
You must carry: Panacea (x 9 )
</lang>
 
=={{header|Racket}}==
 
<lang racket>#lang racket
<lang racket>
#lang racket
 
(struct item (name explanation value weight volume) #:prefab)
Line 3,082 ⟶ 3,203:
 
(call-with-values (λ() (fill-sack items 0.25 25 '() 0))
(λ(sacks total) (for ([s sacks]) (display-sack s total))))</lang>
</lang>
 
{{out}}
<pre>Take 11 gold (bars)
Line 3,103 ⟶ 3,226:
Take 9 panacea (vials of)
GRAND TOTAL: 54500</pre>
 
=={{header|REXX}}==
{{trans|Fortran}}
Line 3,142 ⟶ 3,266:
say left('', 40) "total volume: " maxV / 1
/*stick a fork in it, we're all done. */</lang>
'''output'''<pre> panacea in sack: 0
<pre>
panacea in sack: 0
ichors in sack: 15
gold items in sack: 11
Line 3,149 ⟶ 3,275:
total value: 54500
total weight: 25
total volume: 0.247</pre>
</pre>
 
===displays all solutions===
<lang rexx>/*REXX program solves the knapsack/unbounded problem: highest value, weight, and volume.*/
Line 3,191 ⟶ 3,319:
end /*j*/
/*stick a fork in it, we're all done. */</lang>
'''output'''
'''output'''<pre>▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ solution 1
<pre>
▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ solution 1
panacea in sack: 0
ichors in sack: 15
Line 3,229 ⟶ 3,359:
total value: 54500
total weight: 24.7
total volume: 0.247</pre>
</pre>
 
=={{header|Ruby}}==
Brute force method, {{trans|Tcl}}
Line 3,270 ⟶ 3,402:
end</lang>
{{out}}
<pre>
<pre>The maximal solution has value 54500
The maximal solution has value 54500
ichor= 0, panacea= 9, gold=11 -- weight:24.7, volume=0.247
ichor= 5, panacea= 6, gold=11 -- weight:24.8, volume=0.247
ichor=10, panacea= 3, gold=11 -- weight:24.9, volume=0.247
ichor=15, panacea= 0, gold=11 -- weight:25.0, volume=0.247</pre>
 
=={{header|SAS}}==
This is yet another brute force solution.
Line 3,307 ⟶ 3,441:
var panacea ichor gold vals;
run;</lang>
Output:
Output:<pre> Obs panacea ichor gold vals
<pre>
Obs panacea ichor gold vals
 
1 0 15 11 54500
2 3 10 11 54500
3 6 5 11 54500
4 9 0 11 54500</pre>
</pre>
 
Use SAS/OR:
<lang sas>/* create SAS data set */
Line 3,354 ⟶ 3,492:
for {s in 1.._NSOL_} print {i in ITEMS} NumSelected[i].sol[s];
quit;</lang>
 
MILP solver output:<pre>TotalValue
MILP solver output:
<pre>
TotalValue
54500
 
Line 3,360 ⟶ 3,501:
gold (bars) 11
ichor (ampules of) 0
panacea (vials of) 9 </pre>
</pre>
CLP solver output:<pre>TotalValue
 
CLP solver output:
<pre>
TotalValue
54500
 
Line 3,382 ⟶ 3,527:
gold (bars) 11
ichor (ampules of) 0
panacea (vials of) 9 </pre>
</pre>
 
=={{header|Scala}}==
===Functional approach (Tail recursive)===
<lang Scala>import scala.annotation.tailrec
 
'''Functional approach''' (Tail recursive)
 
<lang scala>import scala.annotation.tailrec
object UnboundedKnapsack extends App {
private val (maxWeight, maxVolume) = (BigDecimal(25.0), BigDecimal(0.25))
private val items = Seq(Item("panacea", 3000, 0.3, 0.025), Item("ichor", 1800, 0.2, 0.015), Item("gold", 2500, 2.0, 0.002))
 
@tailrec
private def packer(notPacked: Seq[Knapsack], packed: Seq[Knapsack]): Seq[Knapsack] = {
def fill(knapsack: Knapsack): Seq[Knapsack] = items.map(i => Knapsack(i +: knapsack.bagged))
 
def stuffer(Seq: Seq[Knapsack]): Seq[Knapsack] = // Cause brute force
Seq.map(k => Knapsack(k.bagged.sortBy(_.name))).distinct
 
if (notPacked.isEmpty) packed.sortBy(-_.totValue).take(4)
else packer(stuffer(notPacked.flatMap(fill)).filter(_.isNotFull), notPacked ++ packed)
}
 
private case class Item(name: String, value: Int, weight: BigDecimal, volume: BigDecimal)
 
private case class Knapsack(bagged: Seq[Item]) {
def isNotFull: Boolean = totWeight <= maxWeight && totVolume <= maxVolume
 
override def toString = s"[${show(bagged)} | value: $totValue, weight: $totWeight, volume: $totVolume]"
 
def totValue: Int = bagged.map(_.value).sum
 
private def totVolume = bagged.map(_.volume).sum
 
private def totWeight = bagged.map(_.weight).sum
 
private def show(is: Seq[Item]) =
(items.map(_.name) zip items.map(i => is.count(_ == i)))
Line 3,420 ⟶ 3,569:
.mkString(", ")
}
 
packer(items.map(i => Knapsack(Seq(i))), Nil).foreach(println)
}</lang>
 
{{Out}}
{{out}}
<pre>[panacea: 0, ichor: 15, gold: 11 | value: 54500, weight: 25.0, volume: 0.247]
 
<pre>
[panacea: 0, ichor: 15, gold: 11 | value: 54500, weight: 25.0, volume: 0.247]
[panacea: 3, ichor: 10, gold: 11 | value: 54500, weight: 24.9, volume: 0.247]
[panacea: 6, ichor: 5, gold: 11 | value: 54500, weight: 24.8, volume: 0.247]
[panacea: 9, ichor: 0, gold: 11 | value: 54500, weight: 24.7, volume: 0.247]</pre>
</pre>
{{Out}}See it in running in your browser by [https://scalafiddle.io/sf/1fRBQs5/2 ScalaFiddle (JavaScript)] or by [https://scastie.scala-lang.org/S4oGElcwQkCMesfuSRKfkw Scastie (JVM).].
 
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
Line 3,481 ⟶ 3,634:
writeln("The weight of this carry is " <& best.weight <& " and the volume used is " <& best.volume digits 4);
end func;</lang>
 
Output:<pre>Maximum value achievable is 54500
Output:
<pre>
Maximum value achievable is 54500
This is achieved by carrying 0 panacea, 15 ichor and 11 gold items
The weight of this carry is 25.0 and the volume used is 0.2470</pre>
</pre>
 
=={{header|Sidef}}==
{{trans|Perl}}
Line 3,552 ⟶ 3,710:
EOT</lang>
{{out}}
<pre>
<pre>Max value 54500, with:
Max value 54500, with:
Item Qty Weight Vol Value
--------------------------------------------------
Line 3,558 ⟶ 3,717:
gold: 11 22 0.022 27500
--------------------------------------------------
Total: 24 0.247 54500</pre>
</pre>
 
=={{header|Tcl}}==
The following code uses brute force, but that's tolerable as long as it takes just a split second to find all 4 solutions. The use of arrays makes the quote quite legible:
Line 3,592 ⟶ 3,753:
}
main $argv</lang>
 
<pre>$ time tclsh85 /Tcl/knapsack.tcl
maxval: 54500, best: {i 0 p 9 g 11} {i 5 p 6 g 11} {i 10 p 3 g 11} {i 15 p 0 g 11}
Line 3,598 ⟶ 3,760:
user 0m0.015s
sys 0m0.015s</pre>
 
=={{header|Ursala}}==
The algorithm is to enumerate all packings with up to the maximum of each item,
Line 3,616 ⟶ 3,779:
 
human_readable = ~&p/*<'panacea','ichor','gold'> solutions</lang>
output:<pre><
<pre><
<'panacea': 0,'ichor': 15,'gold': 11>,
<'panacea': 3,'ichor': 10,'gold': 11>,
<'panacea': 6,'ichor': 5,'gold': 11>,
<'panacea': 9,'ichor': 0,'gold': 11>></pre>
 
=={{header|Visual Basic}}==
See: [[Knapsack Problem/Visual Basic]]
Line 3,656 ⟶ 3,821:
54500 24.8 0.247 6 5 11
54500 24.9 0.247 3 10 11
54500 25 0.247 0 15 11 </pre>
</pre>
 
=={{header|zkl}}==
{{trans|D}}
Line 3,682 ⟶ 3,849:
cprod3 is the Cartesian product of three lists or iterators.
{{out}}
<pre>
<pre>Maximum value achievable is 54,500
Maximum value achievable is 54,500
This is achieved by carrying (one solution): 9 panacea, 0 ichor and 11 gold
The weight to carry is 24.7 and the volume used is 0.247</pre>
</pre>
 
[[Category:Puzzles]]
10,327

edits