-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathpart-two-memoized.js
67 lines (56 loc) · 1.45 KB
/
part-two-memoized.js
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
const path = require('path');
const fs = require('fs');
const _ = require('lodash');
const input = fs
.readFileSync(path.join(__dirname, 'input.txt'), 'utf8')
.toString()
.trim()
.split('\n')
.map((v) => {
return parseInt(v, 10);
});
class Node {
constructor(value, index) {
this.value = value;
this.index = index;
this.connections = [];
}
}
const sorted_input = input.slice(0).sort((a, b) => a - b);
const max = sorted_input[sorted_input.length - 1] + 3;
const items = [0, ...sorted_input, max].map((v, i) => new Node(v, i));
// Build our edges
for (let i = 0; i < items.length; i++) {
const current = items[i];
for (let n = 1; n <= 3; n++) {
const next = items[i + n];
if (!next) break;
if (next.value - current.value <= 3) {
current.connections.push(next);
}
}
}
const _countPaths = _.memoize(
function countPathsInner(u, d, pathCount) {
// If current vertex is same as destination, then increment count
if (u === d) {
pathCount++;
}
// Otherwise recurse through all the adjacent vertices
else {
const node = items[u];
for (let connection of node.connections) {
// Since we cache our result now, add the return value to our carried count
pathCount += _countPaths(connection.index, d, pathCount);
}
}
return pathCount;
},
// Cache by `start / ending` index
(u, d) => `${u},${d}`
);
const countPaths = () => {
return _countPaths(0, items.length - 1, 0);
};
const total = countPaths();
console.log(total);