-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathday22.py
executable file
·66 lines (47 loc) · 1.5 KB
/
day22.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/env python3
import sys
DEAL_NEW, DEAL_INC, CUT = 0, 1, 2
def build_moves(instructions):
moves = []
for l in instructions:
if 'deal into' in l:
moves.append((DEAL_NEW, 0))
elif 'deal with' in l:
n = int(l[l.rfind(' '):])
moves.append((DEAL_INC, n))
elif 'cut' in l:
n = int(l[l.rfind(' '):])
moves.append((CUT, n))
return moves
def transform(start, step, size, moves):
for move, n in moves:
if move == DEAL_NEW:
start = (start - step) % size
step = -step % size
elif move == DEAL_INC:
step = (step * pow(n, size - 2, size)) % size
elif move == CUT:
if n < 0:
n += size
start = (start + step * n) % size
return start, step
def repeat(start, step, size, repetitions):
final_step = pow(step, repetitions, size)
S = (1 - final_step) * pow(1 - step, size - 2, size)
final_start = (start * S) % size
return final_start, final_step
# Open the first argument as input or use stdin if no arguments were given
fin = open(sys.argv[1]) if len(sys.argv) > 1 else sys.stdin
moves = build_moves(fin)
start, step, size = 0, 1, 10007
target_card = 2019
start, step = transform(start, step, size, moves)
position = ((target_card - start) * pow(step, size - 2, size)) % size
print('Part 1:', position)
start, step, size = 0, 1, 119315717514047
target_position = 2020
repetitions = 101741582076661
start, step = transform(start, step, size, moves)
start, step = repeat(start, step, size, repetitions)
card = (start + step * target_position) % size
print('Part 2:', card)