Solve 2020 day 13 CRT jojo
This commit is contained in:
39
2020/d13.py
Normal file
39
2020/d13.py
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
from lib import get_data, str_to_ints, mod_inverse
|
||||||
|
from functools import reduce
|
||||||
|
|
||||||
|
data = get_data(__file__)
|
||||||
|
lines = data.splitlines()
|
||||||
|
|
||||||
|
earliest = int(lines[0])
|
||||||
|
times = str_to_ints(lines[1])
|
||||||
|
|
||||||
|
mintime = 10**21
|
||||||
|
id = None
|
||||||
|
|
||||||
|
for time in times:
|
||||||
|
mintimecur = (earliest // time) * time + time
|
||||||
|
if mintimecur < mintime:
|
||||||
|
mintime = mintimecur
|
||||||
|
id = time
|
||||||
|
|
||||||
|
|
||||||
|
assert id is not None
|
||||||
|
print((mintime - earliest) * id)
|
||||||
|
|
||||||
|
fields = lines[1].split(",")
|
||||||
|
|
||||||
|
buses = []
|
||||||
|
for offset, busid in enumerate(fields):
|
||||||
|
if busid == "x":
|
||||||
|
continue
|
||||||
|
period = int(busid)
|
||||||
|
buses.append((period, -offset % period))
|
||||||
|
|
||||||
|
|
||||||
|
total = 0
|
||||||
|
product = reduce(lambda a, b: a * b, map(lambda x: x[0], buses))
|
||||||
|
for period, offset in buses:
|
||||||
|
p = product // period
|
||||||
|
total += offset * mod_inverse(p, period) * p
|
||||||
|
|
||||||
|
print(total % product)
|
||||||
@@ -148,7 +148,8 @@ Solutions and utility script for Advent of Code challenges in Python.
|
|||||||
- Day 10: 34:27 (so weak)
|
- Day 10: 34:27 (so weak)
|
||||||
- Day 11: 21:05 (hmmm, I rally have to analyze why I am so slow)
|
- Day 11: 21:05 (hmmm, I rally have to analyze why I am so slow)
|
||||||
- Day 12: 21:52 (just slow again for an easy problem)
|
- Day 12: 21:52 (just slow again for an easy problem)
|
||||||
- Day 13:
|
- Day 13: 18:00 (I don't really understand the CRT to be honest)
|
||||||
|
- Day 14:
|
||||||
|
|
||||||
|
|
||||||
## AoC 2022
|
## AoC 2022
|
||||||
|
|||||||
15
lib.py
15
lib.py
@@ -280,3 +280,18 @@ def get_data(filename):
|
|||||||
assert os.path.isfile(txt_file), "Could not download AoC file"
|
assert os.path.isfile(txt_file), "Could not download AoC file"
|
||||||
with open(txt_file) as f:
|
with open(txt_file) as f:
|
||||||
return f.read()
|
return f.read()
|
||||||
|
|
||||||
|
|
||||||
|
def mod_inverse(a, m):
|
||||||
|
def egcd(a, b):
|
||||||
|
if a == 0:
|
||||||
|
return b, 0, 1
|
||||||
|
else:
|
||||||
|
g, y, x = egcd(b % a, a)
|
||||||
|
return g, x - (b // a) * y, y
|
||||||
|
|
||||||
|
g, x, _ = egcd(a, m)
|
||||||
|
if g != 1:
|
||||||
|
raise Exception('Modular inverse does not exist')
|
||||||
|
else:
|
||||||
|
return x % m
|
||||||
|
|||||||
Reference in New Issue
Block a user