-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path202308.py
54 lines (47 loc) · 1.3 KB
/
202308.py
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
import math
paths = {}
with open("202308.txt", "r") as f:
for i, line in enumerate(f):
if i == 0:
dirs = line.strip()
elif i == 1:
continue
else:
[a, b, c, d, e, f, g, h, i] = [x for x in line.strip() if x.isalpha()]
paths["".join([a, b, c])] = ("".join([d, e, f]), "".join([g, h, i]))
idx = 0
steps = 0
cur = "AAA"
while True:
if cur == "ZZZ":
print(f"Part one: {steps}")
break
(left, right) = paths[cur]
if dirs[idx] == "L":
cur = left
elif dirs[idx] == "R":
cur = right
else:
raise ValueError(f"Invalid direction: {dirs[idx]}")
idx = (idx + 1) % len(dirs)
steps += 1
def cycle_length(starting):
idx = 0
steps = 0
cur = starting
while True:
if cur.endswith("Z"):
return steps
(left, right) = paths[cur]
if dirs[idx] == "L":
cur = left
elif dirs[idx] == "R":
cur = right
else:
raise ValueError(f"Invalid direction: {dirs[idx]}")
idx = (idx + 1) % len(dirs)
steps += 1
cycles = {n: cycle_length(n) for n in paths if n.endswith("A")}
assert all(n % len(dirs) == 0 for n in cycles.values())
part_two = math.lcm(*cycles.values())
print(f"Part two: {part_two}")