-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday8.ts
128 lines (104 loc) · 2.44 KB
/
day8.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
function log(u: unknown) {
console.log(JSON.stringify(u, null, ' '));
}
const test_input = `LLR
AAA = (BBB, BBB)
BBB = (AAA, ZZZ)
ZZZ = (ZZZ, ZZZ)`.split('\n');
const test_input2 = `LR
11A = (11B, XXX)
11B = (XXX, 11Z)
11Z = (11B, XXX)
22A = (22B, XXX)
22B = (22C, 22C)
22C = (22Z, 22Z)
22Z = (22B, 22B)
XXX = (XXX, XXX)`.split('\n');
const puzzle_input = `<get from aoc website>`.split('\n');
function part1(input: string[]) {
const directions = input[0];
const map = new Map(
input.slice(2).map((i) => {
const [name, routes] = i.split('=');
const parts = routes.replaceAll(/[)( )]/g, '').split(',');
return [name.trim(), parts];
}),
);
let step = 'AAA';
let index = 0;
const dirCnt = directions.length;
while (step != 'ZZZ') {
const [L, R] = map.get(step) ?? [];
if (L == null || R == null) {
throw new Error('!!');
}
const pick = directions[index % dirCnt];
switch (pick) {
case 'L': {
step = L;
break;
}
case 'R': {
step = R;
break;
}
default:
throw new Error('!!!');
}
index++;
}
log(index);
}
function part2(input: string[]) {
const directions = input[0];
const steps: string[] = [];
const map = new Map(
input.slice(2).map((i) => {
const [name, routes] = i.split('=');
const parts = routes.replaceAll(/[)( )]/g, '').split(',');
const n = name.trim();
if (n.endsWith('A')) {
steps.push(n);
}
return [n, parts];
}),
);
const dirCnt = directions.length;
const cycles = steps.map((step) => {
let index = 0;
let counting = false;
while (!step.endsWith('Z') && !counting) {
if (!counting && step.endsWith('Z')) {
index = 0;
}
counting = counting || step.endsWith('Z');
const pick = directions[index % dirCnt];
const [L, R] = map.get(step) ?? [];
if (L == null || R == null) {
throw new Error('!!');
}
switch (pick) {
case 'L': {
step = L;
break;
}
case 'R': {
step = R;
break;
}
default:
throw new Error('!!!');
}
index++;
}
return index;
});
log(lcm(cycles));
}
function lcm(arr: number[]): number {
return arr.reduce((acc, n) => (acc * n) / gcd(acc, n));
}
function gcd(a: number, b: number): number {
return b === 0 ? a : gcd(b, a % b);
}
part2(puzzle_input);