-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday19.rs
346 lines (291 loc) · 9.22 KB
/
day19.rs
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
//! [Day 19: Aplenty](https://adventofcode.com/2023/day/19)
use core::panic;
use regex::Regex;
use rustc_hash::FxHashMap;
use std::collections::VecDeque;
#[derive(Debug)]
enum Comparison {
Lesser,
Greater,
LesserOrEqual,
GreaterOrEqual,
}
impl Comparison {
fn from(s: &str) -> Self {
match s {
">" => Self::Greater,
"<" => Self::Lesser,
_ => panic!(),
}
}
fn opposite(&self) -> Self {
match &self {
Self::Lesser => Self::GreaterOrEqual,
Self::Greater => Self::LesserOrEqual,
_ => panic!("unused"),
}
}
}
#[derive(Debug)]
enum Rule {
Link(String),
Condition((String, Comparison, u64, String)),
}
struct Puzzle {
workflows: FxHashMap<String, Vec<Rule>>,
parts: Vec<[u64; 4]>,
}
fn new_range(op: &Comparison, n: u64, rating: (u64, u64)) -> (u64, u64) {
let (mut lo, mut hi) = rating;
match op {
Comparison::Greater => lo = (n + 1).max(lo),
Comparison::Lesser => hi = (n - 1).min(hi),
Comparison::GreaterOrEqual => lo = n.max(lo),
Comparison::LesserOrEqual => hi = n.min(hi),
};
(lo, hi)
}
#[derive(Clone)]
struct Ratings {
x: (u64, u64),
m: (u64, u64),
a: (u64, u64),
s: (u64, u64),
}
impl Ratings {
const fn new() -> Self {
Self {
x: (1, 4000),
m: (1, 4000),
a: (1, 4000),
s: (1, 4000),
}
}
const fn is_valid(&self) -> bool {
self.x.0 <= self.x.1 && self.m.0 <= self.m.1 && self.a.0 <= self.a.1 && self.s.0 <= self.s.1
}
const fn product(&self) -> u64 {
(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)
}
fn update_x(&mut self, op: &Comparison, value: u64) -> Self {
let new_x = new_range(op, value, self.x);
self.x = new_range(&op.opposite(), value, self.x);
Self {
x: new_x,
m: self.m,
a: self.a,
s: self.s,
}
}
fn update_m(&mut self, op: &Comparison, value: u64) -> Self {
let new_m = new_range(op, value, self.m);
self.m = new_range(&op.opposite(), value, self.m);
Self {
x: self.x,
m: new_m,
a: self.a,
s: self.s,
}
}
fn update_a(&mut self, op: &Comparison, value: u64) -> Self {
let new_a = new_range(op, value, self.a);
self.a = new_range(&op.opposite(), value, self.a);
Self {
x: self.x,
m: self.m,
a: new_a,
s: self.s,
}
}
fn update_s(&mut self, op: &Comparison, value: u64) -> Self {
let new_s = new_range(op, value, self.s);
self.s = new_range(&op.opposite(), value, self.s);
Self {
x: self.x,
m: self.m,
a: self.a,
s: new_s,
}
}
}
impl Puzzle {
fn new(data: &str) -> Self {
let mut puzzle = Self {
workflows: FxHashMap::default(),
parts: vec![],
};
//
// _ _ _____ _ __ __ _
// | | | | __ \| | \ \ / / | |
// | | | | | \/| | \ V / | |
// | | | | | __ | | \ / | |
// | |_| | |_\ \| |____| | |_|
// \___/ \____/\_____/\_/ (_)
//
let re = Regex::new(r"^\{x=(\d+),m=(\d+),a=(\d+),s=(\d+)\}$").unwrap();
let re2 = Regex::new(r"(\w+)\{(.+)\}$").unwrap();
let re3: Regex = Regex::new(r"^([xmas])([<>])(\d+):(\w+)$").unwrap();
let rule_new = |s: &str| match s {
s if s.chars().all(char::is_alphabetic) => Rule::Link(s.to_string()),
_ => re3.captures(s).map_or_else(
|| {
panic!();
},
|caps| {
let variable = caps.get(1).unwrap().as_str().to_owned();
let op = Comparison::from(caps.get(2).unwrap().as_str());
let value: u64 = caps.get(3).unwrap().as_str().parse().unwrap();
let next = caps.get(4).unwrap().as_str().to_owned();
Rule::Condition((variable, op, value, next))
},
),
};
for line in data.lines() {
if let Some(caps) = re.captures(line) {
let caps: [u64; 4] = caps
.iter()
.skip(1)
.map(|cap| cap.unwrap().as_str().parse::<u64>().unwrap())
.collect::<Vec<_>>()
.as_slice()
.try_into()
.unwrap();
puzzle.parts.push(caps);
} else if let Some(caps) = re2.captures(line) {
let name = caps.get(1).unwrap().as_str().to_string();
let rules: Vec<Rule> = caps
.get(2)
.unwrap()
.as_str()
.split(',')
.map(rule_new)
.collect();
if let Some(Rule::Link(_)) = rules.last() {
} else {
panic!("rule '{line}' must end with a link");
}
puzzle.workflows.insert(name, rules);
}
}
puzzle
}
/// Solve part one.
fn part1(&self) -> u64 {
let mut accepted: u64 = 0;
for xmas in &self.parts {
let mut workflow = "in";
loop {
let rules = &self.workflows[workflow];
workflow = "";
for rule in rules {
match rule {
Rule::Link(link) => {
workflow = link;
break;
}
Rule::Condition((part, op, value, next)) => {
let part = match part.as_str() {
"x" => xmas[0],
"m" => xmas[1],
"a" => xmas[2],
"s" => xmas[3],
_ => unreachable!(),
};
let done = match op {
Comparison::Lesser => part < *value,
Comparison::Greater => part > *value,
_ => unreachable!(),
};
if done {
workflow = next;
break;
}
}
};
}
match workflow {
"" => panic!("no match"),
"A" => {
accepted += xmas.iter().sum::<u64>();
break;
}
"R" => break,
_ => (),
}
}
}
accepted
}
/// Solve part two.
fn part2(&self) -> u64 {
let mut accepted = 0;
let mut q = VecDeque::new();
q.push_back(("in".to_string(), Ratings::new()));
while let Some((workflow, mut ratings)) = q.pop_back() {
if !ratings.is_valid() {
continue;
}
if workflow == "A" {
accepted += ratings.product();
continue;
}
if workflow == "R" {
continue;
}
for rule in &self.workflows[&workflow] {
match rule {
Rule::Link(name) => {
q.push_back((name.clone(), ratings.clone()));
}
Rule::Condition((variable, op, value, link)) => {
match variable.as_str() {
"x" => {
q.push_back((link.clone(), ratings.update_x(op, *value)));
}
"m" => {
q.push_back((link.clone(), ratings.update_m(op, *value)));
}
"a" => {
q.push_back((link.clone(), ratings.update_a(op, *value)));
}
"s" => {
q.push_back((link.clone(), ratings.update_s(op, *value)));
}
_ => panic!(),
};
}
}
}
continue;
}
accepted
}
}
/// # Panics
#[must_use]
pub fn solve(data: &str) -> (u64, u64) {
let puzzle = Puzzle::new(data);
(puzzle.part1(), puzzle.part2())
}
pub fn main() {
let args = aoc::parse_args();
args.run(solve);
}
#[cfg(test)]
mod test {
use super::*;
const TEST_INPUT: &str = include_str!("test.txt");
#[test]
fn test01() {
let puzzle = Puzzle::new(TEST_INPUT);
assert_eq!(puzzle.part1(), 19114);
}
#[test]
fn test02() {
let puzzle = Puzzle::new(TEST_INPUT);
assert_eq!(puzzle.part2(), 167_409_079_868_000);
}
}