简体   繁体   中英

How do i get the name of items in knapsack in knapsack-problem

Here is my javascript code that solves knapsack problem without dynamic programming. I wanted to get the names of items that are in the sack. How do I get it? W = total weight of knapsack, wt = weight of items, val = value of items, n = number of items

function knapSack(W, wt, val, n) {
    if (n == 0 || W == 0) {
        return 0;
    }
    
    if (wt[n-1] > W) {
        return knapSack(W, wt, val, n-1);
    }
    
    else {
        return Math.max(val[n-1] + knapSack(W-wt[n-1], wt, val, n-1),
                        knapSack(W, wt, val, n-1))
    }
}


item = {
name: ['egg', 'jam', 'bread', 'banana', 'cola', 'chewing gum'],
value: [3,2,5,4,3,1]
}
wt = [8, 8, 10, 5, 8, 1] 
W = 20
n = item.priority.length
console.log(knapSack(W, wt, item.value, n)) 

Not being a javascript programmer this is guaranteed to be wrong

    incl = knapSack(W-wt[n-1], wt, val, n-1)
    excl = knapSack(W, wt, val, n-1)
    cur = val[n-1] + incl[0]
    if (cur > excl[0]) {
      incl[0] = cur
      return [ ...incl, items.name[n-1]]
    } else {
      return excl;
    }

Storing the weight in index 0 and the names starting a index 1.

The... is descript here which I was coincidently watching as I saw this question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM