-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathknapsack.js
More file actions
69 lines (62 loc) · 2.58 KB
/
Copy pathknapsack.js
File metadata and controls
69 lines (62 loc) · 2.58 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
var timeComplexity = 0;
//NOTE: assumption is that currentIndex will be called with 0
//TOP DOWN APPROACH
function solveKnapsackBruteForce (profits, weights, capacity, currentIndex) {
timeComplexity++;
//base condition
if (capacity <= 0 || currentIndex >= profits.length) {
return 0;
}
let profit1 = 0;
if (weights[currentIndex] <= capacity)
{
profit1 = profits[currentIndex] + solveKnapsackBruteForce(profits, weights, capacity - weights[currentIndex], currentIndex+1);
}
const profit2 = solveKnapsackBruteForce(profits, weights, capacity, currentIndex+1);
return Math.max(profit1, profit2);
}
//rows represent index in knapsack problem, columns represent capacities
let globalMemo = [];
//TOP DOWN APPROACH
function solveKnapsackMemoization (profits, weights, capacity, currentIndex) {
timeComplexity++;
//base condition
if (capacity <= 0 || currentIndex >= profits.length) {
return 0;
}
if (!!globalMemo[currentIndex])
{
if (!!globalMemo[currentIndex][capacity]) {
timeComplexity--; //because retrieved from pre-computed result
return globalMemo[currentIndex][capacity];
}
}
else {
globalMemo.push(new Array(capacity+1));
}
let profit1 = 0;
if (weights[currentIndex] <= capacity)
{
profit1 = profits[currentIndex] + solveKnapsackMemoization(profits, weights, capacity - weights[currentIndex], currentIndex+1);
}
const profit2 = solveKnapsackMemoization(profits, weights, capacity, currentIndex+1);
const profitForCapacity = Math.max(profit1, profit2);
globalMemo[currentIndex][capacity] = profitForCapacity;
return profitForCapacity;
}
function solveKnapsackBottomUp (profits, weights, capacity) {
}
var profits = [1, 6, 10, 16];
var weights = [1, 2, 3, 5];
timeComplexity = 0;
console.log(`Total knapsack profit Memoization: ---> ${solveKnapsackMemoization(profits, weights, 7,0)}`);
console.log(`Time Complexity with Memoization:${timeComplexity}`);
timeComplexity = 0;
console.log(`Total knapsack profit Memoization: ---> ${solveKnapsackMemoization(profits, weights, 6,0)}`);
console.log(`Time Complexity with Memoization:${timeComplexity}`);
timeComplexity = 0;
console.log(`Total knapsack profit Brute Force: ---> ${solveKnapsackBruteForce(profits, weights, 7,0)}`);
console.log(`Time Complexity with Brute Force:${timeComplexity}`);
timeComplexity = 0;
console.log(`Total knapsack profit Brute Force: ---> ${solveKnapsackBruteForce(profits, weights, 6,0)}`);
console.log(`Time Complexity with Brute Force:${timeComplexity}`);