-
Notifications
You must be signed in to change notification settings - Fork 17
/
day24.py
executable file
·63 lines (48 loc) · 1.31 KB
/
day24.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
#!/usr/bin/env python3
import sys
from collections import deque
from functools import reduce
def skip(file, n):
for _ in range(n):
next(file)
def get_constraints(fin):
constraints = []
stack = deque()
for i in range(14):
skip(fin, 4)
op = next(fin).rstrip()
assert op.startswith('div z '), 'Invalid input!'
if op == 'div z 1':
skip(fin, 10)
op = next(fin)
assert op.startswith('add y '), 'Invalid input!'
a = int(op.split()[-1])
stack.append((i, a))
skip(fin, 2)
else:
op = next(fin)
assert op.startswith('add x '), 'Invalid input!'
b = int(op.split()[-1])
j, a = stack.pop()
constraints.append((i, j, a + b))
skip(fin, 12)
return constraints
def find_max_min(constraints):
nmax = [0] * 14
nmin = [0] * 14
for i, j, diff in constraints:
if diff > 0:
nmax[i], nmax[j] = 9, 9 - diff
nmin[i], nmin[j] = 1 + diff, 1
else:
nmax[i], nmax[j] = 9 + diff, 9
nmin[i], nmin[j] = 1, 1 - diff
nmax = reduce(lambda acc, d: acc * 10 + d, nmax)
nmin = reduce(lambda acc, d: acc * 10 + d, nmin)
return nmax, nmin
# 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
constraints = get_constraints(fin)
nmax, nmin = find_max_min(constraints)
print('Part 1:', nmax)
print('Part 2:', nmin)