-
Notifications
You must be signed in to change notification settings - Fork 0
/
8.1.ts
51 lines (38 loc) · 970 Bytes
/
8.1.ts
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
type Node = {
L: string;
R: string;
};
export function parseInput(
input: string,
): [Array<'L' | 'R'>, Record<string, Node>] {
const lines = input.split(/\r?\n/);
const directions = lines.shift()!.split('') as Array<'L' | 'R'>;
lines.shift();
const nodes = lines.reduce<Record<string, Node>>((nodes, line) => {
const matches = line.match(
/([A-Z0-9]{3})\s=\s\(([A-Z0-9]{3}),\s([A-Z0-9]{3})\)/,
);
if (!matches) {
return nodes;
}
const [, source, L, R] = matches;
nodes[source] = { L, R };
return nodes;
}, {});
return [directions, nodes];
}
export function main(input: string) {
const [directions, nodes] = parseInput(input);
let position = 'AAA';
let direction = 0;
let count = 0;
while (position !== 'ZZZ') {
position = nodes[position][directions[direction]];
count++;
direction++;
if (direction === directions.length) {
direction = 0;
}
}
return count;
}