Knapsack problem/Continuous: Difference between revisions

Content added Content deleted
No edit summary
(Added BBC BASIC)
Line 139: Line 139:
end loop;
end loop;
end Knapsack_Continuous;</lang>
end Knapsack_Continuous;</lang>
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> INSTALL @lib$+"SORTSALIB"
Sort% = FN_sortSAinit(1, 0) : REM Descending
nItems% = 9
maxWeight = 15.0
DIM items{(nItems%-1) name$, weight, price, worth}
FOR item% = 0 TO nItems%-1
READ items{(item%)}.name$, items{(item%)}.weight, items{(item%)}.price
items{(item%)}.worth = items{(item%)}.price / items{(item%)}.weight
NEXT
DATA "beef", 3.8, 36, "pork", 5.4, 43, "ham", 3.6, 90
DATA "greaves", 2.4, 45, "flitch", 4.0, 30, "brawn", 2.5, 56
DATA "welt", 3.7, 67, "salami", 3.0, 95, "sausage", 5.9, 98
C% = nItems% : D% = 0
CALL Sort%, items{()}, items{(0)}.worth
TotalWeight = 0
TotalPrice = 0
FOR i% = 0 TO nItems%-1
IF TotalWeight + items{(i%)}.weight < maxWeight THEN
TotalWeight += items{(i%)}.weight
TotalPrice += items{(i%)}.price
PRINT "Take all the " items{(i%)}.name$
ELSE
weight = maxWeight - TotalWeight
price = weight * items{(i%)}.worth
TotalWeight += weight
TotalPrice += price
PRINT "Take "; weight " kg of " items{(i%)}.name$
EXIT FOR
ENDIF
NEXT
PRINT '"Total weight = " ; TotalWeight " kg"
PRINT "Total price = " ; TotalPrice
END</lang>
Output:
<pre>
Take all the salami
Take all the ham
Take all the brawn
Take all the greaves
Take 3.5 kg of welt

Total weight = 15 kg
Total price = 349.378379
</pre>

=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdio.h>
<lang c>#include <stdio.h>