-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday19.py
208 lines (174 loc) · 7.53 KB
/
day19.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
from __future__ import annotations
from typing import Optional
from collections import deque
import re
from adventofcode import Day
class PartRange:
def __init__(self, x=(1, 4000), m=(1, 4000), a=(1, 4000), s=(1, 4000)):
self.x = x
self.m = m
self.a = a
self.s = s
def branch(self, rule) -> list[(PartRange, str)]:
result = []
match (rule.category, rule.check):
case ('x', '>'):
result.append((PartRange((self.x[0], min(self.x[1], rule.value)), self.m, self.a, self.s), None))
result.append((PartRange((max(self.x[0], rule.value + 1), self.x[1]), self.m, self.a, self.s), rule.dest))
case ('x', '<'):
result.append((PartRange((self.x[0], min(self.x[1], rule.value - 1)), self.m, self.a, self.s), rule.dest))
result.append((PartRange((max(self.x[0], rule.value), self.x[1]), self.m, self.a, self.s), None))
case ('m', '>'):
result.append((PartRange(self.x, (self.m[0], min(self.m[1], rule.value)), self.a, self.s), None))
result.append((PartRange(self.x, (max(self.m[0], rule.value + 1), self.m[1]), self.a, self.s), rule.dest))
case ('m', '<'):
result.append((PartRange(self.x, (self.m[0], min(self.m[1], rule.value - 1)), self.a, self.s), rule.dest))
result.append((PartRange(self.x, (max(self.m[0], rule.value), self.m[1]), self.a, self.s), None))
case ('a', '>'):
result.append((PartRange(self.x, self.m, (self.a[0], min(self.a[1], rule.value)), self.s), None))
result.append((PartRange(self.x, self.m, (max(self.a[0], rule.value + 1), self.a[1]), self.s), rule.dest))
case ('a', '<'):
result.append((PartRange(self.x, self.m, (self.a[0], min(self.a[1], rule.value - 1)), self.s), rule.dest))
result.append((PartRange(self.x, self.m, (max(self.a[0], rule.value), self.a[1]), self.s), None))
case ('s', '>'):
result.append((PartRange(self.x, self.m, self.a, (self.s[0], min(self.s[1], rule.value))), None))
result.append((PartRange(self.x, self.m, self.a, (max(self.s[0], rule.value + 1), self.s[1])), rule.dest))
case ('s', '<'):
result.append((PartRange(self.x, self.m, self.a, (self.s[0], min(self.s[1], rule.value - 1))), rule.dest))
result.append((PartRange(self.x, self.m, self.a, (max(self.s[0], rule.value), self.s[1])), None))
return result
def combinations(self) -> int:
return (self.x[1] - (self.x[0] - 1)) * (self.m[1] - (self.m[0] - 1)) * (self.a[1] - (self.a[0] - 1)) * (self.s[1] - (self.s[0] - 1))
def __repr__(self):
return f'PartRange(x={self.x}, m={self.m}, a={self.a}, s={self.s})'
class Part:
_x = re.compile(r'x=(\d+)')
_m = re.compile(r'm=(\d+)')
_a = re.compile(r'a=(\d+)')
_s = re.compile(r's=(\d+)')
def __init__(self, line):
self.x = int(self._x.search(line).group(1))
self.m = int(self._m.search(line).group(1))
self.a = int(self._a.search(line).group(1))
self.s = int(self._s.search(line).group(1))
def __repr__(self):
return f'Part(x={self.x}, m={self.m}, a={self.a}, s={self.s})'
class Rule:
_parts = re.compile(r'(\w+)([<>])(\d+):(\w+)')
def __init__(self, string):
match = Rule._parts.match(string)
(self.category, self.check, self.value, self.dest) = match.groups()
self.value = int(self.value)
def test(self, part: Part) -> Optional[str]:
match self.category:
case 'x':
test_val = part.x
case 'm':
test_val = part.m
case 'a':
test_val = part.a
case _:
test_val = part.s
match self.check:
case '<':
return self.dest if test_val < self.value else None
case _:
return self.dest if test_val > self.value else None
def __repr__(self):
return f'Rule({self.category}, {self.check}, {self.value}, {self.dest})'
class Workflow:
_name = re.compile(r'(\w+){')
_rule = re.compile(r'(\w+[><]\d+:\w+)')
_dest = re.compile(r',(\w+)}')
def __init__(self, line):
self.name = self._name.match(line).group(1)
self.rules = []
for rule in self._rule.findall(line):
r = Rule(rule)
self.rules.append(r)
pass
self.dest = self._dest.findall(line)[0]
def branch(self, part: PartRange, workflows: dict[str, Workflow]) -> list[(PartRange, Optional[Workflow])]:
result = []
fail_q = deque([part])
for rule in self.rules:
next_q = deque()
while len(fail_q) > 0:
pt = fail_q.popleft()
branches = pt.branch(rule)
for p, wf in branches:
if wf is not None:
if wf == 'R':
pass
elif wf == 'A':
result.append((p, None))
else:
result.append((p, workflows[wf]))
else:
next_q.append(p)
fail_q = next_q
if self.dest == 'A':
result.extend(map(lambda p2: (p2, None), fail_q))
elif self.dest != 'R':
result.extend(map(lambda p2: (p2, workflows[self.dest]), fail_q))
return result
def test(self, part: Part) -> Optional[str]:
for rule in self.rules:
test_result = rule.test(part)
if test_result is not None:
return test_result
return self.dest
def __repr__(self):
return f'Workflow(name={self.name}, rules={self.rules}, dest={self.dest})'
class Day19(Day):
def __init__(self):
super().__init__(2023, 19)
def part01(self):
text = super()._part01_input()
[wfs_text, parts_text] = text.split('\n\n')
wfs = {}
parts = []
for line in wfs_text.splitlines():
wf = Workflow(line)
wfs[wf.name] = wf
for line in parts_text.splitlines():
part = Part(line)
parts.append(part)
accepted = []
rejected = []
for part in parts:
wf = wfs['in']
while wf:
result = wf.test(part)
match result:
case 'R':
rejected.append(part)
wf = None
case 'A':
accepted.append(part)
wf = None
case target:
wf = wfs[target]
return sum([a.x + a.m + a.a + a.s for a in accepted])
def part02(self):
text = super()._part02_input()
[wfs_text, _] = text.split('\n\n')
wfs = {}
for line in wfs_text.splitlines():
wf = Workflow(line)
wfs[wf.name] = wf
accepted = []
wf = wfs['in']
parts = [(PartRange(), wf)]
while len(parts) > 0:
next_parts = []
for _ in range(len(parts)):
(part, wf) = parts.pop()
branches = wf.branch(part, wfs)
for branch in branches:
if branch[1] is None:
accepted.append(branch[0])
else:
next_parts.append(branch)
parts = next_parts
return sum(map(lambda a: a.combinations(), accepted))