-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday20.rs
432 lines (387 loc) · 12 KB
/
day20.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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
use crate::data::load;
use crate::math_utils;
use std::collections::{HashMap, HashSet, VecDeque};
use thiserror::Error;
#[derive(Error, Debug, PartialEq, Eq)]
pub enum PuzzleErr {
#[error("Input parsing error")]
ParseInputError,
#[error("Runtime error")]
RuntimeError,
#[error("An expectation required for Part 2 was violated")]
Part2ExpectationViolated,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Pulse {
High,
Low,
}
#[derive(Debug, Clone)]
struct PulseMsg {
from: String,
to: String,
pulse: Pulse,
}
trait Receiver {
fn receive(&mut self, in_pulse: &PulseMsg) -> Option<VecDeque<PulseMsg>>;
}
#[derive(Debug, Clone)]
struct Broadcast {
name: String,
receivers: Vec<String>,
}
fn _parse_after_arrow(line: &str) -> Vec<String> {
line.trim()
.split("->")
.nth(1)
.unwrap()
.trim()
.split(", ")
.map(|s| s.to_string())
.collect::<Vec<_>>()
}
impl Broadcast {
fn new(receivers: &[String]) -> Self {
Broadcast {
name: "broadcaster".to_string(),
receivers: receivers.to_owned(),
}
}
fn from(line: &str) -> Self {
let receivers = _parse_after_arrow(line);
Self::new(&receivers)
}
}
impl Receiver for Broadcast {
fn receive(&mut self, in_pulse: &PulseMsg) -> Option<VecDeque<PulseMsg>> {
Option::Some(
self.receivers
.iter()
.map(|r| PulseMsg {
from: self.name.clone(),
to: r.clone(),
pulse: in_pulse.pulse,
})
.collect::<VecDeque<_>>(),
)
}
}
#[derive(Debug, Clone)]
struct Conjunction {
name: String,
memory: HashMap<String, Pulse>,
receivers: Vec<String>,
}
impl Conjunction {
fn new(name: &str, receivers: &[String]) -> Self {
Self {
name: name.to_string(),
memory: HashMap::new(),
receivers: receivers.to_owned(),
}
}
fn from(line: &str) -> Self {
let name = line.split("->").nth(0).unwrap().replace('&', "");
let receivers = _parse_after_arrow(line);
Self::new(name.trim(), &receivers)
}
fn add_input(&mut self, new_input: &str) {
self.memory.insert(new_input.to_string(), Pulse::Low);
}
fn add_inputs(&mut self, new_inputs: &HashSet<&str>) {
new_inputs.iter().for_each(|i| self.add_input(i))
}
}
impl Receiver for Conjunction {
fn receive(&mut self, in_pulse: &PulseMsg) -> Option<VecDeque<PulseMsg>> {
self.memory.insert(in_pulse.from.clone(), in_pulse.pulse);
let out_pulse = match self.memory.values().all(|p| p == &Pulse::High) {
true => Pulse::Low,
false => Pulse::High,
};
Option::Some(
self.receivers
.iter()
.map(|r| PulseMsg {
from: self.name.clone(),
to: r.clone(),
pulse: out_pulse,
})
.collect::<VecDeque<_>>(),
)
}
}
#[derive(Debug, Clone)]
struct FlipFlop {
name: String,
state: bool, // true = "on", false = "off"
receivers: Vec<String>,
}
impl FlipFlop {
fn new(name: &str, receivers: &[String]) -> Self {
Self {
name: name.to_string(),
state: false,
receivers: receivers.to_owned(),
}
}
fn from(line: &str) -> Self {
let name = line.split("->").nth(0).unwrap().replace('%', "");
let receivers = _parse_after_arrow(line);
Self::new(name.trim(), &receivers)
}
}
impl Receiver for FlipFlop {
fn receive(&mut self, in_pulse: &PulseMsg) -> Option<VecDeque<PulseMsg>> {
log::trace!(
"FlipFlip {} received {:?} pulse.",
self.name,
in_pulse.pulse
);
if in_pulse.pulse == Pulse::High {
return None;
}
let out_pulse = match self.state {
false => Pulse::High,
true => Pulse::Low,
};
self.state = !self.state;
Option::Some(
self.receivers
.iter()
.map(|r| PulseMsg {
from: self.name.clone(),
to: r.clone(),
pulse: out_pulse,
})
.collect::<VecDeque<_>>(),
)
}
}
#[derive(Debug, Clone)]
struct Output {
name: String,
}
impl Output {
fn new() -> Self {
Self {
name: "output".to_string(),
}
}
}
impl Receiver for Output {
fn receive(&mut self, _: &PulseMsg) -> Option<VecDeque<PulseMsg>> {
Option::None
}
}
#[derive(Debug, Clone)]
enum Module {
B(Broadcast),
C(Conjunction),
F(FlipFlop),
O(Output),
}
fn _parse_input_line(line: &str) -> Result<Module, PuzzleErr> {
if line.starts_with("broadcaster") {
Ok(Module::B(Broadcast::from(line)))
} else if line.starts_with('%') {
Ok(Module::F(FlipFlop::from(line)))
} else if line.starts_with('&') {
Ok(Module::C(Conjunction::from(line)))
} else {
Err(PuzzleErr::ParseInputError)
}
}
fn parse_input(input: &str) -> Result<HashMap<String, Module>, PuzzleErr> {
// Parse the individual modules defined on each line.
let mut modules = input
.trim()
.lines()
.map(_parse_input_line)
.collect::<Result<Vec<_>, PuzzleErr>>()?;
// Manually add the `Output` module.
modules.push(Module::O(Output::new()));
// Convert the vector into a dictionary.
let mut mapping = modules
.into_iter()
.map(|m| {
let x: (String, Module) = match m {
Module::B(ref a) => (a.name.clone(), m),
Module::C(ref a) => (a.name.clone(), m),
Module::F(ref a) => (a.name.clone(), m),
Module::O(ref a) => (a.name.clone(), m),
};
x
})
.collect::<HashMap<String, Module>>();
// Get inputs for Conjugation modules.
let mut receiver_connections = HashMap::<String, HashSet<&str>>::new();
let duplicate_mapping = mapping.clone();
for (name, module) in duplicate_mapping.iter() {
let recievers = match module {
Module::B(b) => b.receivers.clone(),
Module::F(f) => f.receivers.clone(),
Module::C(c) => c.receivers.clone(),
_ => Vec::new(),
};
recievers.iter().for_each(|r| {
receiver_connections
.entry(r.to_string())
.and_modify(|s| {
s.insert(name.as_str());
})
.or_insert(HashSet::from_iter([name.as_str()]));
});
}
for (receiver, input_mods) in receiver_connections.iter() {
if let Some(Module::C(c)) = mapping.get_mut(receiver) {
c.add_inputs(input_mods)
}
}
Ok(mapping)
}
struct PulseCounter {
low: u32,
high: u32,
}
impl PulseCounter {
fn new() -> Self {
Self { low: 0, high: 0 }
}
fn track(&mut self, pulse_msg: &PulseMsg) {
match pulse_msg.pulse {
Pulse::Low => self.low += 1,
Pulse::High => self.high += 1,
}
}
}
pub fn puzzle_1(input: &str, n_button_presses: u32) -> Result<u32, PuzzleErr> {
// Parse modules from input.
let mut modules = parse_input(input)?;
// Tracker for the total number of pulses.
let mut pulse_counter = PulseCounter::new();
// Perform button presses.
for _ in 0..n_button_presses {
let mut pulses = VecDeque::from_iter([PulseMsg {
from: "button".to_string(),
to: "broadcaster".to_string(),
pulse: Pulse::Low,
}]);
pulse_counter.low += 1;
while !pulses.is_empty() {
let pulse = pulses.pop_front().unwrap();
log::trace!("PULSE: {:?}", pulse);
if let Some(response) = match modules.get_mut(&pulse.to) {
Some(Module::B(b)) => b.receive(&pulse),
Some(Module::C(c)) => c.receive(&pulse),
Some(Module::F(f)) => f.receive(&pulse),
Some(Module::O(o)) => o.receive(&pulse),
None => None,
} {
log::trace!("Received {} responses.", response.len());
response.into_iter().for_each(|r| {
log::trace!("RESPONSE: {:?}", r);
pulse_counter.track(&r);
pulses.push_back(r);
});
}
}
}
log::info!(
"Final counts: {} low, {} high",
pulse_counter.low,
pulse_counter.high
);
Ok(pulse_counter.low * pulse_counter.high)
}
pub fn puzzle_2(input: &str) -> Result<u64, PuzzleErr> {
// Parse modules from input.
let mut modules = parse_input(input)?;
// Get the input module for "rx" module.
let rx_input = modules
.values()
.filter(|m| match m {
Module::C(c) => c.receivers.contains(&"rx".to_string()),
_ => false,
})
.collect::<Vec<_>>()
.first()
.cloned()
.unwrap();
log::info!("'rx' module input: {:?}", rx_input);
// Dict for the memory inputs of the "rx" input.
// Will count how many button presses until set "HIGH".
let rx_input_inputs = match rx_input {
Module::C(c) => Ok(c.memory.keys().cloned().collect::<HashSet<_>>()),
_ => Err(PuzzleErr::Part2ExpectationViolated),
}?;
log::info!("inputs to 'rx' input: {:?}", rx_input_inputs);
let mut rx_input_presses = HashMap::<String, u32>::new();
for num_presses in 1..u32::MAX {
let mut pulses = VecDeque::from_iter([PulseMsg {
from: "button".to_string(),
to: "broadcaster".to_string(),
pulse: Pulse::Low,
}]);
while !pulses.is_empty() {
let pulse = pulses.pop_front().unwrap();
// Record num. button presses for HIGH pulses from inputs to input of "rx".
if (pulse.pulse == Pulse::High)
& rx_input_inputs.contains(&pulse.from)
& !rx_input_presses.contains_key(&pulse.from)
{
log::info!(
"Recording {} presses for module {}",
num_presses,
pulse.from
);
rx_input_presses.insert(pulse.from.clone(), num_presses);
}
// All inputs to the input for "rx" found a HIGH pulse.
if rx_input_inputs
.iter()
.all(|i| rx_input_presses.contains_key(i))
{
log::info!(
"Found button presses for all 'rx' input inputs: {:?}.",
rx_input_presses
);
return Ok(math_utils::lcm(
rx_input_presses
.values()
.map(|x| *x as u64)
.collect::<Vec<_>>(),
));
}
// Send pulse and add responses to queue.
if let Some(response) = match modules.get_mut(&pulse.to) {
Some(Module::B(b)) => b.receive(&pulse),
Some(Module::C(c)) => c.receive(&pulse),
Some(Module::F(f)) => f.receive(&pulse),
Some(Module::O(o)) => o.receive(&pulse),
None => None,
} {
response.into_iter().for_each(|r| pulses.push_back(r));
}
}
}
unreachable!();
}
pub fn main(data_dir: &str) {
println!("Day 20: Pulse Propagation");
let data = load(data_dir, 20, None);
// Puzzle 1.
let answer_1 = puzzle_1(&data, 1000);
match answer_1 {
Ok(x) => println!(" Puzzle 1: {}", x),
Err(e) => panic!("No solution to puzzle 1: {}.", e),
}
assert_eq!(answer_1, Ok(944750144));
// Puzzle 2.
let answer_2 = puzzle_2(&data);
match answer_2 {
Ok(x) => println!(" Puzzle 2: {}", x),
Err(e) => panic!("No solution to puzzle 2: {}", e),
}
assert_eq!(answer_2, Ok(222718819437131))
}