-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
98 lines (91 loc) · 2.42 KB
/
index.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
import run from "aocrunner";
const parseInput = (rawInput: string) => rawInput;
const directionsMap: Record<string, string> = { L: "0", R: "1" };
const part1 = (rawInput: string): number => {
const [directionsString, elementsString] = parseInput(rawInput).split("\n\n");
const directions = directionsString
.replace(/[LR]/g, (m) => directionsMap[m])
.split("")
.map(Number);
const elements = elementsString.split("\n").reduce((a: Record<string, string[]>, b) => {
const [key, mapString] = b.split(" = ");
const map = mapString.replace(/[()]/g, "").split(", ");
return { ...a, [key]: map };
}, {});
let position = "AAA";
let step = 0;
while (position !== "ZZZ") {
for (const direction of directions) {
position = elements[position][direction];
step += 1;
if (position === "ZZZ") {
break;
}
}
}
return step;
};
const part2 = (rawInput: string): number => {
const [directionsString, elementsString] = parseInput(rawInput).split("\n\n");
const directions = directionsString
.replace(/[LR]/g, (m) => directionsMap[m])
.split("")
.map(Number);
const elements = elementsString.split("\n").reduce((a: Record<string, string[]>, b) => {
const [key, mapString] = b.split(" = ");
const map = mapString.replace(/[()]/g, "").split(", ");
return { ...a, [key]: map };
}, {});
const AKeys = Object.keys(elements).filter((key) => key[2] === "A");
const AZSteps = AKeys.map((key) => {
let position = key;
let step = 0;
while (position[2] !== "Z") {
for (const direction of directions) {
position = elements[position][direction];
step += 1;
if (position[2] === "Z") {
break;
}
}
}
return step;
});
const gcd = (a: number, b: number): number => (b == 0 ? a : gcd(b, a % b));
const lcm = (a: number, b: number) => (a / gcd(a, b)) * b;
const lcmAll = (ns: number[]) => ns.reduce(lcm, 1);
return lcmAll(AZSteps);
};
run({
part1: {
tests: [
{
input: `LLR
AAA = (BBB, BBB)
BBB = (AAA, ZZZ)
ZZZ = (ZZZ, ZZZ)`,
expected: 6,
},
],
solution: part1,
},
part2: {
tests: [
{
input: `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)`,
expected: 6,
},
],
solution: part2,
},
trimTestInputs: true,
onlyTests: false,
});