Added Solution for 2023 day 20

This commit is contained in:
Burnus 2023-12-20 20:09:20 +01:00
parent a8dc1a90cb
commit e341db7a22
5 changed files with 447 additions and 0 deletions

View file

@ -0,0 +1,15 @@
[package]
name = "day20_pulse_propagation"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
[dev-dependencies]
criterion = "0.5.1"
[[bench]]
name = "test_benchmark"
harness = false

View file

@ -0,0 +1,148 @@
With your help, the Elves manage to find the right parts and fix all of the machines. Now, they just need to send the command to boot up the machines and get the sand flowing again.
The machines are far apart and wired together with long *cables*. The cables don't connect to the machines directly, but rather to communication *modules* attached to the machines that perform various initialization tasks and also act as communication relays.
Modules communicate using *pulses*. Each pulse is either a *high pulse* or a *low pulse*. When a module sends a pulse, it sends that type of pulse to each module in its list of *destination modules*.
There are several different types of modules:
*Flip-flop* modules (prefix `%`) are either *on* or *off*; they are initially *off*. If a flip-flop module receives a high pulse, it is ignored and nothing happens. However, if a flip-flop module receives a low pulse, it *flips between on and off*. If it was off, it turns on and sends a high pulse. If it was on, it turns off and sends a low pulse.
*Conjunction* modules (prefix `&`) *remember* the type of the most recent pulse received from *each* of their connected input modules; they initially default to remembering a *low pulse* for each input. When a pulse is received, the conjunction module first updates its memory for that input. Then, if it remembers *high pulses* for all inputs, it sends a *low pulse*; otherwise, it sends a *high pulse*.
There is a single *broadcast module* (named `broadcaster`). When it receives a pulse, it sends the same pulse to all of its destination modules.
Here at Desert Machine Headquarters, there is a module with a single button on it called, aptly, the *button module*. When you push the button, a single *low pulse* is sent directly to the `broadcaster` module.
After pushing the button, you must wait until all pulses have been delivered and fully handled before pushing it again. Never push the button if modules are still processing pulses.
Pulses are always processed *in the order they are sent*. So, if a pulse is sent to modules `a`, `b`, and `c`, and then module `a` processes its pulse and sends more pulses, the pulses sent to modules `b` and `c` would have to be handled first.
The module configuration (your puzzle input) lists each module. The name of the module is preceded by a symbol identifying its type, if any. The name is then followed by an arrow and a list of its destination modules. For example:
```
broadcaster -> a, b, c
%a -> b
%b -> c
%c -> inv
&inv -> a
```
In this module configuration, the broadcaster has three destination modules named `a`, `b`, and `c`. Each of these modules is a flip-flop module (as indicated by the `%` prefix). `a` outputs to `b` which outputs to `c` which outputs to another module named `inv`. `inv` is a conjunction module (as indicated by the `&` prefix) which, because it has only one input, acts like an inverter (it sends the opposite of the pulse type it receives); it outputs to `a`.
By pushing the button once, the following pulses are sent:
```
button -low-> broadcaster
broadcaster -low-> a
broadcaster -low-> b
broadcaster -low-> c
a -high-> b
b -high-> c
c -high-> inv
inv -low-> a
a -low-> b
b -low-> c
c -low-> inv
inv -high-> a
```
After this sequence, the flip-flop modules all end up *off*, so pushing the button again repeats the same sequence.
Here's a more interesting example:
```
broadcaster -> a
%a -> inv, con
&inv -> b
%b -> con
&con -> output
```
This module configuration includes the `broadcaster`, two flip-flops (named `a` and `b`), a single-input conjunction module (`inv`), a multi-input conjunction module (`con`), and an untyped module named `output` (for testing purposes). The multi-input conjunction module `con` watches the two flip-flop modules and, if they're both on, sends a *low pulse* to the `output` module.
Here's what happens if you push the button once:
```
button -low-> broadcaster
broadcaster -low-> a
a -high-> inv
a -high-> con
inv -low-> b
con -high-> output
b -high-> con
con -low-> output
```
Both flip-flops turn on and a low pulse is sent to `output`! However, now that both flip-flops are on and `con` remembers a high pulse from each of its two inputs, pushing the button a second time does something different:
```
button -low-> broadcaster
broadcaster -low-> a
a -low-> inv
a -low-> con
inv -high-> b
con -high-> output
```
Flip-flop `a` turns off! Now, `con` remembers a low pulse from module `a`, and so it sends only a high pulse to `output`.
Push the button a third time:
```
button -low-> broadcaster
broadcaster -low-> a
a -high-> inv
a -high-> con
inv -low-> b
con -low-> output
b -low-> con
con -high-> output
```
This time, flip-flop `a` turns on, then flip-flop `b` turns off. However, before `b` can turn off, the pulse sent to `con` is handled first, so it *briefly remembers all high pulses* for its inputs and sends a low pulse to `output`. After that, flip-flop `b` turns off, which causes `con` to update its state and send a high pulse to `output`.
Finally, with `a` on and `b` off, push the button a fourth time:
```
button -low-> broadcaster
broadcaster -low-> a
a -low-> inv
a -low-> con
inv -high-> b
con -high-> output
```
This completes the cycle: `a` turns off, causing `con` to remember only low pulses and restoring all modules to their original states.
To get the cables warmed up, the Elves have pushed the button `1000` times. How many pulses got sent as a result (including the pulses sent by the button itself)?
In the first example, the same thing happens every time the button is pushed: `8` low pulses and `4` high pulses are sent. So, after pushing the button `1000` times, `8000` low pulses and `4000` high pulses are sent. Multiplying these together gives `*32000000*`.
In the second example, after pushing the button `1000` times, `4250` low pulses and `2750` high pulses are sent. Multiplying these together gives `*11687500*`.
Consult your module configuration; determine the number of low pulses and high pulses that would be sent after pushing the button `1000` times, waiting for all pulses to be fully handled after each push of the button. *What do you get if you multiply the total number of low pulses sent by the total number of high pulses sent?*
Your puzzle answer was `836127690`.
\--- Part Two ---
----------
The final machine responsible for moving the sand down to Island Island has a module attached named `rx`. The machine turns on when a *single low pulse* is sent to `rx`.
Reset all modules to their default states. Waiting for all pulses to be fully handled after each button press, *what is the fewest number of button presses required to deliver a single low pulse to the module named `rx`?*
Your puzzle answer was `240914003753369`.
Both parts of this puzzle are complete! They provide two gold stars: \*\*
At this point, you should [return to your Advent calendar](/2023) and try another puzzle.
If you still want to see it, you can [get your puzzle input](20/input).

View file

@ -0,0 +1,221 @@
use core::fmt::Display;
use std::collections::HashMap;
#[derive(Debug, PartialEq, Eq)]
pub enum ParseError<'a> {
InvalidType(char),
LineMalformed(&'a str),
}
impl Display for ParseError<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::InvalidType(c) => write!(f, "Module types can only be %, &, or broadcaster. Found {c} instead."),
Self::LineMalformed(v) => write!(f, "Line is malformed: {v}"),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Signal { High, Low, }
#[derive(Clone, PartialEq, Eq)]
enum ModuleType {
FlipFlop(Signal),
Conjunction(HashMap<usize, Signal>),
Broadcast,
}
#[derive(Clone)]
struct Module {
id: usize,
module_type: ModuleType,
outputs: Vec<usize>,
}
pub fn run(input: &str) -> Result<(usize, usize), ParseError> {
let mut modules = try_parse_modules(input)?;
let mut results = Vec::new();
let (mut low_count, mut high_count, mut rx_idx) = (0, 0, 0);
let rx_trigger = modules.iter().find(|m| m.outputs.contains(&1)).map(|m| m.id).unwrap();
let trigger_triggers: Vec<_> = modules.iter().filter(|m| m.outputs.contains(&rx_trigger)).map(|m| m.id).collect();
let mut trigger_trigger_indexes = vec![0; trigger_triggers.len()];
for press in 0.. {
let this = push_button(&mut modules, &trigger_triggers);
if press < 1000 {
low_count += this.0;
high_count += this.1;
results.push((low_count, high_count));
}
this.2.iter().enumerate().filter(|(_idx, res)| **res).for_each(|(idx, _res)| {
if trigger_trigger_indexes[idx] == 0 {
trigger_trigger_indexes[idx] = press+1;
if trigger_trigger_indexes.iter().all(|count| count > &0) {
rx_idx = trigger_trigger_indexes.iter().cloned().reduce(lcm).unwrap();
}
}
});
if press >= 1000 && rx_idx > 0 {
break;
}
}
let first = low_count*high_count;
let second = rx_idx;
Ok((first, second))
}
fn lcm(lhs: usize, rhs: usize) -> usize {
lhs * rhs / gcd(lhs, rhs)
}
fn gcd(lhs: usize, rhs: usize) -> usize {
let (mut a, mut b) = (lhs, rhs);
while b != 0 {
(a, b) = (b, a%b);
}
a
}
fn try_parse_modules(input: &str) -> Result<Vec<Module>, ParseError> {
let mut ids = HashMap::from([("output", 0), ("rx", 1), ("roadcaster", 2)]);
let mut modules = Vec::from([Module{ id: 0, module_type: ModuleType::Broadcast, outputs: Vec::new() }, Module{ id: 1, module_type: ModuleType::Broadcast, outputs: Vec::new()}]);
for line in input.lines() {
let components: Vec<_> = line.split([' ', ',']).collect();
if components.len() < 3 || components[0].len() < 2 {
return Err(ParseError::LineMalformed(line));
}
let module_type = match components[0].chars().next() {
Some('b') => Ok(ModuleType::Broadcast),
Some('%') => Ok(ModuleType::FlipFlop(Signal::Low)),
Some('&') => Ok(ModuleType::Conjunction(HashMap::new())),
Some(e) => Err(ParseError::InvalidType(e)),
None => unreachable!(),
}?;
let name = &components[0][1..];
let id = match ids.get(&name) {
Some(i) => *i,
None => {
let l = ids.len();
ids.insert(name, l);
l
},
};
let outputs = components.iter().skip(2).step_by(2).map(|dest| {
match ids.get(dest) {
Some(i) => *i,
None => {
let l = ids.len();
ids.insert(dest, l);
l
},
}
}).collect();
modules.push(Module{ id, module_type, outputs, });
}
modules.sort_by_key(|module| module.id);
for idx in 0..modules.len() {
if matches!(modules[idx].module_type, ModuleType::Conjunction(_)) {
let init = modules.iter().filter(|module| module.outputs.contains(&modules[idx].id)).map(|module| (module.id, Signal::Low)).collect();
modules[idx].module_type = ModuleType::Conjunction(init);
}
}
Ok(modules)
}
fn push_button(modules: &mut [Module], watch_list: &[usize]) -> (usize, usize, Vec<bool>) {
let (mut send_low, mut send_high) = (Vec::from([(2, 2)]), Vec::new());
let (mut low_count, mut high_count) = (0, 0);
let mut watch_results = vec![false; watch_list.len()];
while !send_low.is_empty() || !send_high.is_empty() {
low_count += send_low.len();
high_count += send_high.len();
(send_low, send_high) = tick(modules, &send_low, &send_high);
watch_list.iter().enumerate().for_each(|(idx, id)| if send_high.iter().any(|(from, _to)| from == id) { watch_results[idx] = true; });
}
(low_count, high_count, watch_results)
}
fn tick(modules: &mut [Module], low_to_send: &[(usize, usize)], high_to_send: &[(usize, usize)]) -> (Vec<(usize, usize)>, Vec<(usize, usize)>) {
let (mut next_low, mut next_high) = (Vec::new(), Vec::new());
low_to_send.iter().for_each(|(from_idx, to_idx)| {
let next = send_low(*from_idx, *to_idx, modules);
match next.1 {
Signal::Low => next.0.iter().for_each(|next_to_idx| { next_low.push((*to_idx, *next_to_idx)); }),
Signal::High => next.0.iter().for_each(|next_to_idx| { next_high.push((*to_idx, *next_to_idx)); }),
};
});
high_to_send.iter().for_each(|(from_idx, to_idx)| {
let next = send_high(*from_idx, *to_idx, modules);
match next.1 {
Signal::Low => next.0.iter().for_each(|next_to_idx| { next_low.push((*to_idx, *next_to_idx)); }),
Signal::High => next.0.iter().for_each(|next_to_idx| { next_high.push((*to_idx, *next_to_idx)); }),
};
});
(next_low, next_high)
}
fn send_low(from_idx: usize, to_idx: usize, modules: &mut [Module]) -> (Vec<usize>, Signal) {
let curr = modules[to_idx].clone();
match curr.module_type {
ModuleType::Broadcast => (curr.outputs.to_vec(), Signal::Low),
ModuleType::FlipFlop(Signal::Low) => {
modules[to_idx].module_type = ModuleType::FlipFlop(Signal::High);
(curr.outputs.to_vec(), Signal::High)
},
ModuleType::FlipFlop(Signal::High) => {
modules[to_idx].module_type = ModuleType::FlipFlop(Signal::Low);
(curr.outputs.to_vec(), Signal::Low)
},
ModuleType::Conjunction(inputs) => {
let mut new = inputs;
new.insert(from_idx, Signal::Low);
modules[to_idx].module_type = ModuleType::Conjunction(new);
(curr.outputs.to_vec(), Signal::High)
},
}
}
fn send_high(from_idx: usize, to_idx: usize, modules: &mut [Module]) -> (Vec<usize>, Signal) {
let curr = modules[to_idx].clone();
match curr.module_type {
ModuleType::Broadcast => (curr.outputs.to_vec(), Signal::High),
ModuleType::FlipFlop(_) => (Vec::new(), Signal::High),
ModuleType::Conjunction(inputs) => {
let mut new = inputs;
new.insert(from_idx, Signal::High);
modules[to_idx].module_type = ModuleType::Conjunction(new.clone());
if new.iter().all(|(_idx, input)| input == &Signal::High) {
(curr.outputs.to_vec(), Signal::Low)
} else {
(curr.outputs.to_vec(), Signal::High)
}
},
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::read_to_string;
fn read_file(name: &str) -> String {
read_to_string(name).expect(&format!("Unable to read file: {name}")[..]).trim().to_string()
}
#[test]
fn test_sample() {
let sample_input = read_file("tests/sample_input");
assert_eq!(run(&sample_input), Ok((11687500, 1)));
}
#[test]
fn test_challenge() {
let challenge_input = read_file("tests/challenge_input");
assert_eq!(run(&challenge_input), Ok((836127690, 240914003753369)));
}
}

View file

@ -0,0 +1,58 @@
%ng -> vz
%hv -> zz
%cn -> fv, kp
%sc -> sm
&rt -> jf, hv, bs, kt, fn
%bc -> fv
%sb -> gk
%vz -> gk, lg
%sm -> mx
%kp -> fv, pq
&gk -> mx, sc, vq, bz, ng, zk, sm
%bs -> rt, mk
%pn -> rt
%rq -> sl, xd
%jr -> fv, bc
%vm -> rt, pn
%rk -> gk, sb
%gs -> xt
%dc -> sl
%bz -> gk, sc
%ql -> sl, fz
%kt -> bt
%gn -> fv, hk
broadcaster -> bs, rq, cn, bz
%rl -> rh, gk
&hj -> rx
%vj -> rt, rr
%jx -> fv, bf
&ks -> hj
%rh -> gk, vq
%hk -> jx
%fn -> vj
%jl -> mr, sl
%vq -> ng
%mr -> sl, dc
%fk -> cc
%jc -> fk, sl
&jf -> hj
%lg -> gk, rk
%zz -> jg, rt
%pq -> lx, fv
%xt -> gn
%bf -> fv, jr
&qs -> hj
%gv -> sl, jl
%bt -> rt, fn
%mm -> sl, ql
%jg -> vm, rt
%lx -> gs
%rr -> hv, rt
&fv -> xt, qs, gs, cn, lx, hk
%mx -> rl
&zk -> hj
&sl -> fk, rq, fz, xd, ks
%fz -> jc
%mk -> rt, kt
%xd -> mm
%cc -> sl, gv

View file

@ -0,0 +1,5 @@
broadcaster -> a
%a -> inv, con
&inv -> b
%b -> con
&con -> rx