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
|
#advent of code 2020
#day 13
#kinda cheated, the chinese remainder theorem (CRT) was copy-pasted from google search results
#the source where I was reading how it works didn't really provide a good example
#will definitely look it up later :)
def gcd_extended(a, b):
if a == 0:
return b, 0, 1
gcd, x1, y1 = gcd_extended(b % a, a)
x = y1 - (b // a) * x1
y = x1
return gcd, x, y
def find_min_x(num, rem):
prod = 1
for n in num:
prod *= n
result = 0
for i in range(len(num)):
prod_i = prod // num[i]
_, inv_i, _ = gcd_extended(prod_i, num[i])
result += rem[i] * prod_i * inv_i
return result % prod
PuzzleInput = open("13.in","r").read().split("\n");
timestamp = int(PuzzleInput[0]);
buses = PuzzleInput[1].split(",");f b != "x"];
times = dict();
BusList = [];
OffsetList = [];
for index, bus in enumerate(buses):
if bus == "x": continue;
bus = int(bus);
BusList.append(bus);
OffsetList.append(bus-index);
d = timestamp%bus;
NextStop = timestamp-d+bus;
times[NextStop] = (bus,bus-d);
busID, WaitTime = times[min(times)];
p1 = busID * WaitTime;
p2 = find_min_x(BusList,OffsetList); #CRT
print("part 1 =",p1);
print("part 2 =",p2);
|