generated from mariotacke/template-advent-of-code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart2.js
32 lines (26 loc) · 801 Bytes
/
part2.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
const gcd = (a, b) => a ? gcd(b % a, a) : b;
const lcm = (a, b) => a * b / gcd(a, b);
module.exports = (input) => {
const lines = input.split('\n').map((line) => line.trim());
const instructions = lines[0].split('').map((x) => x === 'L' ? 0 : 1);
const map = lines.slice(2).reduce((m, line) => {
const [, node, left, right] = /(\w{3}) = \((\w{3}), (\w{3})\)/.exec(line);
return {
...m,
[node]: [left, right],
};
}, {});
const next = (step) => step % instructions.length;
return Object
.keys(map)
.filter((key) => key.endsWith('A'))
.map((startNode) => {
let node = startNode;
let step = 0;
while (!node.endsWith('Z')) {
node = map[node][instructions[next(step++)]];
}
return step;
})
.reduce(lcm);
};