forked from akshitagit/JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0-1-knapSack.js
More file actions
98 lines (79 loc) · 2.4 KB
/
0-1-knapSack.js
File metadata and controls
98 lines (79 loc) · 2.4 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Recursive solution
let knapsackRecursive = function (profits, weights, capacity, currentIndex) {
if (capacity <= 0 || currentIndex >= profits.length) {
return 0;
}
// include current element
let profit1 = 0;
if (weights[currentIndex] <= capacity) {
profit1 =
profits[currentIndex] +
knapsackRecursive(
profits,
weights,
capacity - weights[currentIndex],
currentIndex + 1
);
}
// exclude current element
let profit2 = knapsackRecursive(profits, weights, capacity, currentIndex + 1);
return Math.max(profit1, profit2);
};
// Top Down with memoisation
const dp = [];
let knapsackTopDown = function (profits, weights, capacity, currentIndex) {
if (capacity <= 0 || currentIndex >= profits.length) {
return 0;
}
dp[currentIndex] = dp[currentIndex] || [];
if (dp[currentIndex][capacity]) {
return dp[currentIndex][capacity];
}
// include current element
let profit1 = 0;
if (weights[currentIndex] <= capacity) {
profit1 =
profits[currentIndex] +
knapsackTopDown(
profits,
weights,
capacity - weights[currentIndex],
currentIndex + 1
);
}
// exclude current element
let profit2 = knapsackTopDown(profits, weights, capacity, currentIndex + 1);
dp[currentIndex][capacity] = Math.max(profit1, profit2);
return dp[currentIndex][capacity];
};
// Bottom Up with tabulation
let knapsackBottomUp = function (profits, weights, capacity) {
const dp = new Array(profits.length)
.fill(0)
.map(() => Array(capacity + 1).fill(0));
for (let c = 1; c <= capacity; c++) {
dp[0][c] = c >= weights[0] ? profits[0] : 0;
}
for (let i = 1; i < profits.length; i++) {
for (let c = 1; c <= capacity; c++) {
dp[i][c] =
c >= weights[i]
? Math.max(dp[i - 1][c], profits[i] + dp[i - 1][c - weights[i]])
: dp[i - 1][c];
}
}
return dp[profits.length - 1][capacity];
};
let solveKnapsack = function (profits, weights, capacity) {
// return knapsackRecursive(profits, weights, capacity, 0);
// return knapsackTopDown(profits, weights, capacity, 0);
return knapsackBottomUp(profits, weights, capacity);
};
var profits = [1, 6, 10, 16];
var weights = [1, 2, 3, 5];
console.log(
`Total knapsack profit: ---> ${solveKnapsack(profits, weights, 7)}`
);
console.log(
`Total knapsack profit: ---> ${solveKnapsack(profits, weights, 6)}`
);