Knapsack problem/Continuous: Difference between revisions

Line 1,476:
 
=={{header|Run BASIC}}==
<lang runbasic>x</lang>dim name$(9)
dim wgt(9)
dim price(9)
dim tak$(100)
 
name$(1) = "beef" : wgt(1) = 3.8 : price(1) = 36
name$(2) = "pork" : wgt(2) = 5.4 : price(2) = 43
name$(3) = "ham" : wgt(3) = 3.6 : price(3) = 90
name$(4) = "greaves" : wgt(4) = 2.4 : price(4) = 45
name$(5) = "flitch" : wgt(5) = 4.0 : price(5) = 30
name$(6) = "brawn" : wgt(6) = 2.5 : price(6) = 56
name$(7) = "welt" : wgt(7) = 3.7 : price(7) = 67
name$(8) = "salami" : wgt(8) = 3.0 : price(8) = 95
name$(9) = "sausage" : wgt(9) = 5.9 : price(9) = 98
 
for beef = 0 to 15 step 3.8
for pork = 0 to 15 step 5.4
for ham = 0 to 15 step 3.6
for greaves = 0 to 15 step 2.4
for flitch = 0 to 15 step 4.0
for brawn = 0 to 15 step 2.5
for welt = 0 to 15 step 3.7
for salami = 0 to 15 step 3.0
for sausage = 0 to 15 step 5.9
if beef + pork + ham + greaves + flitch + brawn + welt + salami + sausage <= 15 then
totPrice = beef / 3.8 * 36 + _
pork / 5.4 * 43 + _
ham / 3.6 * 90 + _
greaves / 2.4 * 45 + _
flitch / 4.0 * 30 + _
brawn / 2.5 * 56 + _
welt / 3.7 * 67 + _
salami / 3.0 * 95 + _
sausage / 5.9 * 98
if totPrice >= maxPrice then
maxPrice = totPrice
theMax = max(totPrice,maxPrice)
t = t + 1
tak$(t) = str$(maxPrice);",";beef;",";pork;",";ham;",";greaves;",";flitch;",";brawn;",";welt;",";salami;",";sausage
end if
end if
next:next :next :next :next :next :next :next :next
 
print "Best 2 Options":print
for i = t-1 to t
totTake = val(word$(tak$(i),1,","))
if totTake > 0 then
totWgt = 0
for j = 2 to 10
wgt = val(word$(tak$(i),j,","))
totWgt = totWgt + wgt
value = wgt / wgt(j - 1) * price(j - 1)
if wgt <> 0 then print name$(j-1);chr$(9);"Value: ";using("###.#",value);chr$(9);"Weight: ";using("##.#",wgt)
next j
print "-------- Total ";using("###.#",totTake);chr$(9);"Weight: ";totWgt
end if
next i</lang>Output:
<pre>Best 2 Options
 
salami Value: 285.0 Weight: 9.0
sausage Value: 98.0 Weight: 5.9
-------- Total 383.0 Weight: 14.9
 
salami Value: 475.0 Weight: 15.0
-------- Total 475.0 Weight: 15.0</pre>
 
=={{header|Tcl}}==
Anonymous user