-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path8.mjs
55 lines (47 loc) · 1.25 KB
/
8.mjs
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
import { readInput } from "./utils.mjs";
const input = readInput(import.meta);
const parseInput = (input) => {
const lines = input.split("\n");
const ins = lines[0];
const nodes = {};
for (let i = 2; i < lines.length; i++) {
const [node, str2] = lines[i].split(" = ");
const [L, R] = str2.slice(1, -1).split(", ");
nodes[node] = { L, R };
}
return { ins, nodes };
};
const gcd = (a, b) => {
for (let temp = b; b !== 0; ) {
b = a % b;
a = temp;
temp = b;
}
return a;
};
const lcm = (a, b) => {
const gcdValue = gcd(a, b);
return (a * b) / gcdValue;
};
const solve2 = (input) => {
const { ins, nodes } = parseInput(input);
let steps = 0;
const startingNodes = Object.keys(nodes).filter((name) => name.endsWith("A"));
const paths = startingNodes.map((node) => [node]);
const loops = {};
while (true) {
const dir = ins[steps % ins.length];
steps++;
for (const [i, path] of paths.entries()) {
const nextNode = nodes[path.at(-1)][dir];
paths[i].push(nextNode);
if (nextNode.endsWith("Z")) {
loops[i] = steps;
}
if (Object.keys(loops).length === startingNodes.length) {
return Object.values(loops).reduce(lcm);
}
}
}
};
console.log(solve2(input));