Skip to content

Commit 5261d58

Browse files
committed
knapSack dp
1 parent 5a38075 commit 5261d58

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

chapter11/05-KnapsackProblemDP.js

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
function knapSack(capacity, weights, values, n) {
2+
3+
var i, w, a, b, kS = [];
4+
5+
for (i = 0; i <= n; i++) {
6+
kS[i] = [];
7+
}
8+
9+
for (i = 0; i <= n; i++){
10+
for (w = 0; w <= capacity; w++){
11+
if (i == 0 || w == 0){
12+
kS[i][w] = 0;
13+
14+
} else if (weights[i-1] <= w){
15+
a = values[i-1] + kS[i-1][w-weights[i-1]];
16+
b = kS[i-1][w];
17+
kS[i][w] = (a > b) ? a : b; //max(a,b)
18+
console.log(a + ' can be part of the solution');
19+
} else{
20+
kS[i][w] = kS[i-1][w];
21+
}
22+
}
23+
console.log(kS[i].join());
24+
}
25+
26+
//extra algorithm to find the items that are part of the solution
27+
findValues(n, capacity, kS, values, weights);
28+
29+
return kS[n][capacity];
30+
}
31+
32+
function findValues(n, capacity, kS, weights, values){
33+
var i=n, k=capacity;
34+
35+
console.log('Items that are part of the solution:');
36+
37+
while (i>0 && k>0){
38+
if (kS[i][k] !== kS[i-1][k]){
39+
console.log('item '+i+' can be part of solution w,v: ' + weights[i-1] + ',' + values[i-1]);
40+
i--;
41+
k = k - kS[i][k];
42+
} else {
43+
i--;
44+
}
45+
}
46+
}
47+
48+
var values = [3,4,5],
49+
weights = [2,3,4],
50+
capacity = 5,
51+
n = values.length;
52+
53+
console.log('Total value that can be carried: ' + knapSack(capacity, weights, values, n));

0 commit comments

Comments
 (0)