forked from algorithm-visualizer/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.js
More file actions
65 lines (61 loc) · 1.58 KB
/
Copy pathcode.js
File metadata and controls
65 lines (61 loc) · 1.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
// import visualization libraries {
const { Tracer, Array2DTracer, LogTracer, Randomize, Layout, VerticalLayout } = require('algorithm-visualizer');
// }
// define tracer variables {
const tracer = new Array2DTracer();
const logger = new LogTracer();
Layout.setRoot(new VerticalLayout([tracer, logger]));
const integer = Randomize.Integer({ min: 5, max: 14 });
const D = [];
const A = [];
for (let i = 0; i <= integer; i++) {
D.push([]);
D[0][i] = 1;
D[i][1] = 1;
for (let j = 0; j <= integer; j++) D[i][j] = 0;
}
tracer.set(D);
Tracer.delay();
// }
function partition(A, n, p) {
// logger {
if (n === 0) logger.println(`[${A.join(', ')}]`);
// }
else {
let end = n;
if (p !== 0 && A[p - 1] < n) end = A[p - 1];
for (let i = end; i > 0; i--) {
A[p] = i;
partition(A, n - i, p + 1);
}
}
}
function integerPartition(n) {
// Calculate number of partitions for all numbers from 1 to n
for (let i = 2; i <= n; i++) {
// We are allowed to use numbers from 2 to i
for (let j = 1; j <= i; j++) {
// Number of partitions without j number + number of partitions with max j
// visualize {
tracer.select(i, j);
Tracer.delay();
// }
D[i][j] = D[i][j - 1] + D[i - j][Math.max(j, i - j)];
// visualize {
tracer.patch(i, j, D[i][j]);
Tracer.delay();
tracer.depatch(i, j);
tracer.deselect(i, j);
// }
}
}
return D[n][n];
}
// logger {
logger.println(`Partitioning: ${integer}`);
// }
partition(A, integer, 0);
const part = integerPartition(integer);
// logger {
logger.println(part);
// }