-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathday16.py
executable file
·84 lines (59 loc) · 1.82 KB
/
day16.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#!/usr/bin/env python3
import sys
import re
from math import prod
class DoubleRange:
__slots__ = ('a', 'b', 'c', 'd')
def __init__(self, a, b, c, d):
self.a, self.b, self.c, self.d = a, b, c, d
def __contains__(self, value):
return self.a <= value <= self.b or self.c <= value <= self.d
def parse_input(fin):
ranges = []
num_exp = re.compile(r'\d+')
for line in map(str.rstrip, fin):
if not line:
break
numbers = map(int, num_exp.findall(line))
ranges.append(DoubleRange(*numbers))
fin.readline()
my_ticket = tuple(map(int, fin.readline().split(',')))
fin.readline()
fin.readline()
tickets = []
for line in fin:
tickets.append(tuple(map(int, line.split(','))))
return ranges, my_ticket, tickets
def invalid_fields(ticket):
for value in ticket:
if all(value not in rng for rng in ranges):
yield value
def is_valid(ticket):
return all(any(v in r for r in ranges) for v in ticket)
def simplify(possible):
assigned = [None] * len(possible)
while any(possible):
for i, poss in enumerate(possible):
if len(poss) == 1:
assigned[i] = match = poss.pop()
break
for other in possible:
if match in other:
other.remove(match)
return assigned
# 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
ranges, my_ticket, tickets = parse_input(fin)
total = sum(map(sum, map(invalid_fields, tickets)))
print('Part 1:', total)
tickets.append(my_ticket)
n_fields = len(my_ticket)
possible = [set(range(n_fields)) for _ in range(len(ranges))]
for ticket in filter(is_valid, tickets):
for rng, poss in zip(ranges, possible):
for i, value in enumerate(ticket):
if value not in rng and i in poss:
poss.remove(i)
indexes = simplify(possible)[:6]
total = prod(my_ticket[i] for i in indexes)
print('Part 2:', total)