RosettaCodeData/Task/Knapsack-problem-Continuous/Phix/knapsack-problem-continuous...

31 lines
844 B
Plaintext

constant meats = {
--Item Weight (kg) Price (Value)
{"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}}
function by_weighted_value(integer i, j)
atom {?,weighti,pricei} = meats[i],
{?,weightj,pricej} = meats[j]
return compare(pricej/weightj,pricei/weighti)
end function
sequence tags = custom_sort(routine_id("by_weighted_value"),tagset(length(meats)))
atom w = 15, worth = 0
for i=1 to length(tags) do
object {desc,wi,price} = meats[tags[i]]
atom c = min(wi,w)
printf(1,"%3.1fkg%s of %s\n",{c,iff(c=wi?" (all)":""),desc})
worth += (c/wi)*price
w -= c
if w=0 then exit end if
end for
printf(1,"Total value: %f\n",{worth})