_TITLE "Shopping Cart Mod of Knapsack Problem/0-1 from Rosetta Code" ' b+ 2020-10-14 ' mod from: "Knapsack problem/0-1 - Rosetta Code Better Solution" 'b+
' ref: http://rosettacode.org/wiki/Knapsack_problem/0-1
' 2020-10-04 post Knapsack - Rosetta Code.bas
' https://www.qb64.org/forum/index.php?topic=3091.msg123665#msg123665
' 2020-10-13 Knapsack better soln 2020-10-13 Rosetta Code
' swap DATA beer,52,10 for DATA xtra_paper,3,1 to trip up original code solution and test better code soln.
' note: need to keep number at 22 to fit default screen 0.
' post https://www.qb64.org/forum/index.php?topic=3091.msg123962#msg123962
' 2020-10-14 Shopping Cart Mod bplus Knapsack solution sucks!
' It will not serve as a general solution or method to approach problems like this.
' The DATA just happens to work well with sort and pick method
' ========================= Here is a counter example with 100 weight limit =======================
' Obviously you should pickup the crackers only!
' Make the 100 weight limit with a carry out value of 100!
'===================================================================================================
READ insert.
name, insert.weight
, insert.value
insert.vPerW = insert.value / insert.weight
loadSort insert, it()
PRINT " *** Shopping Cart Items Sorted by Value Per Unit Weight ***" PRINT " #: Item: Wght: Val: V/W: Packed or Not: Accum w: Value Packed:" IF totW
+ it
(i
).weight
<= 100 THEN pack = -1: totW = totW + it(i).weight: totV = totV + it(i).value
pack = 0
'DATA "ham,20,25"
'DATA "crackers,100,100"
'DATA "ice cream,20,9"
'DATA "potatoes,70,66"
'DATA "beans,30,17"
'DATA "carrots,20,19"
'DATA "cookies,10,5"
SUB loadSort
(insertN
AS item
, dynArr
() AS item
) ' modified for this code 'note this leaves dynArr(0) empty! so ubound of array is also number of items in list
IF insertN.vPerW
> dynArr
(j
).vPerW
THEN ' GT to LT according to descending or ascending sort dynArr(k) = dynArr(k - 1)
dynArr(j) = insertN