Files
python-aoc-2020/day13/part2.py
Sebastian Seedorf e6dd5f4450 Day 13 (reduce)
2020-12-13 18:20:32 +01:00

26 lines
580 B
Python

from functools import reduce
from math import gcd
def lcm(a, b):
return abs(a*b) // gcd(a, b)
# f(n)=an+b and f(m)=xm+y
# Intersection of 2 sequences -> ck+d
def merge(a, b, x, y):
while b != y:
if b < y:
b += a * ((y-b-1) // a + 1)
else:
y += x * ((b-y-1) // x + 1)
d = b
c = lcm(a, x)
return c, d
lines = [x.strip() for x in open("input.txt")]
busses = ((int(x), -idx) for idx, x in enumerate(lines[1].split(',')) if x != 'x')
sequence = reduce(lambda fn, fm: merge(*fn, *fm), busses, (1, 0))
print(sequence[1])