-
Notifications
You must be signed in to change notification settings - Fork 207
Expand file tree
/
Copy pathcode.js
More file actions
92 lines (87 loc) · 2.53 KB
/
Copy pathcode.js
File metadata and controls
92 lines (87 loc) · 2.53 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
// import visualization libraries {
const { Tracer, Array1DTracer, Array2DTracer, LogTracer, Layout, VerticalLayout } = require('algorithm-visualizer');
// }
const val = [1, 4, 5, 7]; // The value of all available items
const wt = [1, 3, 4, 5]; // The weights of available items
const W = 7; // The maximum weight we can carry in our collection
const N = val.length;
const DP = new Array(N + 1);
for (let i = 0; i < N + 1; i++) {
DP[i] = new Array(W + 1);
for (let j = 0; j < W + 1; j++) {
DP[i][j] = 0;
}
}
// define tracer variables {
const tracer = new Array2DTracer('Knapsack Table');
const valuesTracer = new Array1DTracer('Values');
const weightsTracer = new Array1DTracer('Weights');
const logger = new LogTracer();
Layout.setRoot(new VerticalLayout([tracer, valuesTracer, weightsTracer, logger]));
tracer.set(DP);
valuesTracer.set(val);
weightsTracer.set(wt);
Tracer.delay();
// }
for (let i = 0; i <= N; i++) {
for (let j = 0; j <= W; j++) {
if (i === 0 || j === 0) {
/*
If we have no items or maximum weight we can take in collection is 0
then the total weight in our collection is 0
*/
DP[i][0] = 0;
// visualize {
tracer.patch(i, j, DP[i][j]);
Tracer.delay();
tracer.depatch(i, j);
// }
} else if (wt[i - 1] <= j) { // take the current item in our collection
// visualize {
weightsTracer.select(i - 1);
valuesTracer.select(i - 1);
Tracer.delay();
tracer.select(i - 1, j - wt[i - 1]);
tracer.select(i - 1, j);
Tracer.delay();
// }
const A = val[i - 1] + DP[i - 1][j - wt[i - 1]];
const B = DP[i - 1][j];
/*
find the maximum of these two values
and take which gives us a greater weight
*/
if (A > B) {
DP[i][j] = A;
// visualize {
tracer.patch(i, j, DP[i][j]);
Tracer.delay();
// }
} else {
DP[i][j] = B;
// visualize {
tracer.patch(i, j, DP[i][j]);
Tracer.delay();
// }
}
// visualize {
// opt subproblem depatch
tracer.depatch(i, j);
tracer.deselect(i - 1, j);
tracer.deselect(i - 1, j - wt[i - 1]);
valuesTracer.deselect(i - 1);
weightsTracer.deselect(i - 1);
// }
} else { // leave the current item from our collection
DP[i][j] = DP[i - 1][j];
// visualize {
tracer.patch(i, j, DP[i][j]);
Tracer.delay();
tracer.depatch(i, j);
// }
}
}
}
// logger {
logger.println(` Best value we can achieve is ${DP[N][W]}`);
// }