forked from loiane/javascript-datastructures-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathknapsack.js
41 lines (40 loc) · 1.09 KB
/
knapsack.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
function findValues(n, capacity, kS) {
let i = n;
let k = capacity;
// console.log('Items that are part of the solution:');
while (i > 0 && k > 0) {
if (kS[i][k] !== kS[i - 1][k]) {
// console.log(
// item ' + i + ' can be part of solution w,v: ' + weights[i - 1] + ',' + values[i - 1]
// );
i--;
k -= kS[i][k];
} else {
i--;
}
}
}
export function knapSack(capacity, weights, values, n) {
const kS = [];
for (let i = 0; i <= n; i++) {
kS[i] = [];
}
for (let i = 0; i <= n; i++) {
for (let w = 0; w <= capacity; w++) {
if (i === 0 || w === 0) {
kS[i][w] = 0;
} else if (weights[i - 1] <= w) {
const a = values[i - 1] + kS[i - 1][w - weights[i - 1]];
const b = kS[i - 1][w];
kS[i][w] = a > b ? a : b; // max(a,b)
// console.log(a + ' can be part of the solution');
} else {
kS[i][w] = kS[i - 1][w];
}
}
// console.log(kS[i].join());
}
// extra algorithm to find the items that are part of the solution
findValues(n, capacity, kS);
return kS[n][capacity];
}