Skip to content

Instantly share code, notes, and snippets.

@vadim2404
Created December 9, 2023 19:50
Show Gist options
  • Save vadim2404/834ca2fefa254ab6d23a02622dd3b3dc to your computer and use it in GitHub Desktop.
Save vadim2404/834ca2fefa254ab6d23a02622dd3b3dc to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import re
from itertools import cycle
map = {}
ROUTE = re.compile(r"^(\w{3}) = \((\w{3}), (\w{3})\)$")
index_map = {
'L': 0,
'R': 1,
}
points = []
cycles = []
def gcd(a: int, b: int) -> int:
while b:
a, b = b, a % b
return a
def lcm(a: int, b: int) -> int:
return a * b // gcd(a, b)
with open("input.txt") as f:
instructions = f.readline().strip()
f.readline()
for line in f:
line = line.strip()
route = ROUTE.match(line)
map[route.group(1)] = (route.group(2), route.group(3))
if route.group(1)[-1] == 'A':
points.append(route.group(1))
for i, route in enumerate(cycle(instructions), start=1):
idx = index_map[route]
to_remove = []
for j in range(len(points)):
points[j] = map[points[j]][idx]
if points[j][-1] == 'Z':
cycles.append(i)
to_remove.append(j)
for j in to_remove[::-1]:
del points[j]
if not points:
break
for i in range(len(cycles) - 1):
cycles[i + 1] = lcm(cycles[i], cycles[i + 1])
print(cycles[-1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment