-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaoc23_day8_2.py
executable file
·70 lines (49 loc) · 1.34 KB
/
aoc23_day8_2.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/env python
def read_graph():
graph = {}
while True:
try:
line = input()
except EOFError:
break
node, rest = line.split(' = ')
a, b = rest.split(', ')
graph[node] = [a.lstrip('('), b.rstrip(')')]
return graph
def find_length(current, instructions, graph):
# I took a small leap of faith thinking that the path from the start to the
# first time we find the target forms a cycle, it turned out to work
i = 0
n = len(instructions)
while not current.endswith('Z'):
inst = instructions[i % n]
index = 0 if inst == 'L' else 1
current = graph[current][index]
i += 1
return i
def gcd(a, b):
if a > b:
a, b = b, a
while a > 0:
a, b = b % a, a
return b
def lcm(a, b):
return a * b // gcd(a, b)
def solve(instructions, graph):
currents = [item for item in graph if item.endswith('A')]
paths_length = []
for current in currents:
paths_length.append(find_length(current, instructions, graph))
res = paths_length[0]
for x in paths_length[1:]:
res = lcm(res, x)
return res
def main():
instructions = input()
# empty line
input()
graph = read_graph()
res = solve(instructions, graph)
print(res)
if __name__ == '__main__':
main()