forked from loiane/javascript-datastructures-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathknapsack.ts
51 lines (44 loc) · 1.2 KB
/
knapsack.ts
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
42
43
44
45
46
47
48
49
50
51
export function knapSack(capacity: number, weights: number[], values: number[], n: number) {
const kS: Array<Array<number>> = [];
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];
}
function findValues(
n: number,
capacity: number,
kS: Array<Array<number>>
) {
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 = k - kS[i][k];
} else {
i--;
}
}
}