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
|
import fs from "fs";
const [directions, _, ...lines] = fs
.readFileSync("./input.txt")
.toString()
.split("\n")
.slice(0, -1);
const nodes = lines
.map((line) => {
const match = line.match(/(...) = \((...), (...)\)/);
if (!match) throw new Error("Could not match");
return {
node: match[1],
left: match[2],
right: match[3],
};
})
.map((node, index, nodes) => ({
node: index,
left: nodes.findIndex((n) => n.node === node.left),
right: nodes.findIndex((n) => n.node === node.right),
}));
const targetNumber = lines.findIndex((line) => line.startsWith("ZZZ"));
let currentNumber = lines.findIndex((line) => line.startsWith("AAA"));
let steps = 0;
while (currentNumber !== targetNumber) {
const direction = (
{
L: "left",
R: "right",
} as const
)[directions[steps % directions.length]];
if (!direction) throw new Error("Invalid direction");
currentNumber = nodes[currentNumber][direction];
steps++;
}
console.log({ steps });
|