-
Notifications
You must be signed in to change notification settings - Fork 0
/
8.py
51 lines (43 loc) · 1.51 KB
/
8.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
from AoCLibrary import *
with open("input8.txt") as f:
real_input = f.read()
def main(a : str):
a = a.strip()
inp = AdventInput(data=a)
G = {}
instructions = inp.lines[0]
for line in inp.lines[2:]:
start, left, right = re.findall(r'\w+', line)
G[start] = (left, right)
return search(G, instructions), search2(G, instructions, [node for node in G if node.endswith('A')])
def search(G, instructions):
fringe = deque([('AAA', 0, 0)])
while fringe:
node, instruct_pos, steps = fringe.popleft()
if node == 'ZZZ':
return steps
if instructions[instruct_pos%len(instructions)] == 'L':
fringe.append((G[node][0], instruct_pos + 1, steps + 1))
else:
fringe.append((G[node][1], instruct_pos + 1, steps + 1))
assert False
def search2(G, instructions, all_starting_positions:list[str]):
fringe = deque()
for start in all_starting_positions:
fringe.append((start, 0, 0))
spot_to_steps = {}
while fringe:
node, instruct_pos, steps = fringe.popleft()
if node.endswith("Z"):
spot_to_steps[node] = steps
continue
if instructions[instruct_pos%len(instructions)] == 'L':
fringe.append((G[node][0], instruct_pos + 1, steps + 1))
else:
fringe.append((G[node][1], instruct_pos + 1, steps + 1))
return lcm(*spot_to_steps.values())
if "s" in sys.argv:
exit()
result = main(real_input)
if result is not None:
ans(result)