344 lines
10 KiB
Rust
344 lines
10 KiB
Rust
use aoc_runner_derive::aoc;
|
|
use std::collections::{BinaryHeap, HashMap, VecDeque};
|
|
use std::fmt::Display;
|
|
use std::hash::{Hash, Hasher};
|
|
use std::str::Lines;
|
|
|
|
use lazy_regex::lazy_regex;
|
|
use num::integer::lcm;
|
|
|
|
// PARSE
|
|
|
|
const MODULE_PATTERN: lazy_regex::Lazy<lazy_regex::Regex> = lazy_regex!("^([%&]?)([a-z]+) -> ([a-z, ]+)$");
|
|
|
|
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
|
|
enum PulseType {
|
|
Low,
|
|
High,
|
|
}
|
|
|
|
impl From<bool> for PulseType {
|
|
fn from(value: bool) -> Self {
|
|
match value {
|
|
true => PulseType::High,
|
|
false => PulseType::Low,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl From<PulseType> for bool {
|
|
fn from(value: PulseType) -> Self {
|
|
match value {
|
|
PulseType::High => true,
|
|
PulseType::Low => false,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Display for PulseType {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
match self {
|
|
PulseType::Low => f.write_str("low"),
|
|
PulseType::High => f.write_str("high"),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy)]
|
|
enum ModuleKind {
|
|
FlipFlop,
|
|
Conjunction,
|
|
Broadcast,
|
|
Button,
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
struct Module {
|
|
name: String,
|
|
kind: Option<ModuleKind>,
|
|
inputs: Vec<String>,
|
|
outputs: Vec<String>,
|
|
on: bool,
|
|
last_input_states: Vec<PulseType>,
|
|
}
|
|
|
|
impl Hash for Module {
|
|
fn hash<H: Hasher>(&self, state: &mut H) {
|
|
// the only states that change are 'on' and 'last_input_states', the rest are constant once created
|
|
self.on.hash(state);
|
|
self.last_input_states.hash(state);
|
|
}
|
|
}
|
|
|
|
impl Module {
|
|
fn new(name: String) -> Self {
|
|
Self {
|
|
name,
|
|
kind: None,
|
|
inputs: Vec::new(),
|
|
outputs: Vec::new(),
|
|
on: false,
|
|
last_input_states: Vec::new(),
|
|
}
|
|
}
|
|
fn source_idx(&self, name: &str) -> usize {
|
|
self.inputs.iter().position(|in_name| in_name == name).unwrap()
|
|
}
|
|
fn with_kind(name: String, kind: ModuleKind) -> Self {
|
|
let mut m = Self::new(name);
|
|
m.kind = Some(kind);
|
|
m
|
|
}
|
|
fn and_destinations(mut self, destinations: &str) -> Self {
|
|
for dest in destinations.split(", ") {
|
|
self.outputs.push(dest.into());
|
|
}
|
|
self
|
|
}
|
|
fn and_source(mut self, source: String) -> Self {
|
|
self.add_source(source);
|
|
self
|
|
}
|
|
fn add_source(&mut self, source: String) {
|
|
self.inputs.push(source);
|
|
self.last_input_states.push(PulseType::Low);
|
|
}
|
|
fn reset(&mut self) {
|
|
// relevant state is on and last_input_states
|
|
self.on = false;
|
|
for input in &mut self.last_input_states {
|
|
*input = PulseType::Low;
|
|
}
|
|
}
|
|
#[allow(unused)]
|
|
fn state_space(&self) -> u128 {
|
|
match self.kind {
|
|
Some(ModuleKind::Broadcast) | Some(ModuleKind::Button) => 1,
|
|
Some(ModuleKind::FlipFlop) => 2,
|
|
Some(ModuleKind::Conjunction) => 1 << self.last_input_states.len(), // 2^n
|
|
None => 1,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl From<&str> for Module {
|
|
fn from(s: &str) -> Self {
|
|
let Some(re_result) = MODULE_PATTERN.captures(s) else {
|
|
panic!("unparseable module: {}", s);
|
|
};
|
|
let (_, [kind, name, destinations]) = re_result.extract();
|
|
if name == "broadcaster" {
|
|
return Module::with_kind(name.into(), ModuleKind::Broadcast).and_destinations(destinations);
|
|
};
|
|
match kind {
|
|
"%" => Module::with_kind(name.into(), ModuleKind::FlipFlop).and_destinations(destinations),
|
|
"&" => Module::with_kind(name.into(), ModuleKind::Conjunction).and_destinations(destinations),
|
|
_ => panic!("invalid module kind {}", kind),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
struct Job {
|
|
signal: PulseType,
|
|
targets: Vec<String>,
|
|
from: String,
|
|
priority: usize,
|
|
}
|
|
|
|
impl PartialEq for Job {
|
|
fn eq(&self, other: &Self) -> bool {
|
|
self.priority == other.priority
|
|
}
|
|
}
|
|
impl Eq for Job {}
|
|
|
|
impl PartialOrd for Job {
|
|
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
|
other.priority.partial_cmp(&self.priority)
|
|
}
|
|
}
|
|
|
|
impl Ord for Job {
|
|
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
|
self.partial_cmp(other).unwrap()
|
|
}
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
struct Machine {
|
|
modules: HashMap<String, Module>,
|
|
work_queue: BinaryHeap<Job>,
|
|
count_low: u64,
|
|
count_high: u64,
|
|
}
|
|
|
|
impl From<Lines<'_>> for Machine {
|
|
fn from(mut lines: Lines<'_>) -> Self {
|
|
let mut modules = HashMap::from([(
|
|
"button".into(),
|
|
Module::with_kind("button".into(), ModuleKind::Button).and_destinations("broadcaster"),
|
|
)]);
|
|
while let Some(line) = lines.next() {
|
|
let mut module = Module::from(line);
|
|
for output in &module.outputs {
|
|
if let Some(output_mod) = modules.get_mut(output) {
|
|
// already exists, push to input list
|
|
output_mod.add_source(module.name.to_owned());
|
|
} else {
|
|
// forward declaration of 'unknown' modules
|
|
modules.insert(
|
|
output.clone(),
|
|
Module::new(output.clone()).and_source(module.name.clone()),
|
|
);
|
|
}
|
|
}
|
|
if let Some(existing_mod) = modules.get(&module.name) {
|
|
module.inputs = existing_mod.inputs.clone(); // might have been pre-prepared, the rest we take ours
|
|
module.last_input_states = existing_mod.last_input_states.clone();
|
|
}
|
|
modules.insert(module.name.clone(), module);
|
|
}
|
|
|
|
Machine {
|
|
modules,
|
|
work_queue: BinaryHeap::new(),
|
|
count_low: 0,
|
|
count_high: 0,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Machine {
|
|
fn press_button(&mut self) {
|
|
self.send_pulse(PulseType::Low, "broadcaster", "button", 1);
|
|
}
|
|
fn send_pulse(&mut self, signal: PulseType, target: &str, from: &str, priority: usize) {
|
|
// count pulse when it is received
|
|
match signal {
|
|
PulseType::Low => self.count_low += 1,
|
|
PulseType::High => self.count_high += 1,
|
|
};
|
|
match self.modules[target].kind {
|
|
Some(ModuleKind::Button) | Some(ModuleKind::Broadcast) => {
|
|
self.send_all_outputs(PulseType::Low, target, priority)
|
|
}
|
|
Some(ModuleKind::FlipFlop) => match signal {
|
|
PulseType::High => (),
|
|
PulseType::Low => {
|
|
let new_state = !self.modules.get_mut(target).unwrap().on;
|
|
self.modules.get_mut(target).unwrap().on = new_state;
|
|
self.send_all_outputs(new_state.into(), target, priority)
|
|
}
|
|
},
|
|
Some(ModuleKind::Conjunction) => {
|
|
let target_m = self.modules.get_mut(target).unwrap();
|
|
let source_idx = target_m.source_idx(from);
|
|
target_m.last_input_states[source_idx] = signal;
|
|
if target_m.last_input_states.iter().all(|state| *state == PulseType::High) {
|
|
self.send_all_outputs(PulseType::Low, target, priority)
|
|
} else {
|
|
self.send_all_outputs(PulseType::High, target, priority)
|
|
}
|
|
}
|
|
None => (),
|
|
}
|
|
}
|
|
fn send_all_outputs(&mut self, signal: PulseType, from: &str, priority: usize) {
|
|
self.work_queue.push(Job {
|
|
signal,
|
|
targets: self.modules[from].outputs.iter().map(|op| op.to_owned()).collect(),
|
|
from: from.to_owned(),
|
|
priority: priority + 1,
|
|
})
|
|
}
|
|
fn run(&mut self) {
|
|
while let Some(job) = self.work_queue.pop() {
|
|
for target in job.targets {
|
|
self.send_pulse(job.signal, &target, &job.from, job.priority);
|
|
}
|
|
}
|
|
}
|
|
// the number of cycles it took until the target sends a low pulse, or None if the target node sent no low pulses but the job finished
|
|
fn time_to_state(&mut self, goal: &str, state: PulseType) -> Option<u64> {
|
|
while let Some(job) = self.work_queue.pop() {
|
|
if job.from == goal && job.signal == state {
|
|
return Some(self.count_high + self.count_low);
|
|
}
|
|
for target in job.targets {
|
|
self.send_pulse(job.signal, &target, &job.from, job.priority);
|
|
}
|
|
}
|
|
None
|
|
}
|
|
fn reset(&mut self) {
|
|
for (_name, m) in &mut self.modules {
|
|
m.reset();
|
|
}
|
|
self.count_low = 0;
|
|
self.count_high = 0;
|
|
}
|
|
#[allow(unused)]
|
|
fn state_space(&self) -> u128 {
|
|
self.modules.values().map(|m| m.state_space()).product()
|
|
}
|
|
}
|
|
|
|
// PROBLEM 1 solution
|
|
const PROBLEM1_ITERATIONS: usize = 1000;
|
|
#[aoc(day20, part1)]
|
|
fn part1(input: &str) -> u64 {
|
|
let mut machine = Machine::from(input.lines());
|
|
for _ in 0..PROBLEM1_ITERATIONS {
|
|
machine.press_button();
|
|
machine.run();
|
|
}
|
|
machine.count_low * machine.count_high
|
|
}
|
|
|
|
// PROBLEM 2 solution
|
|
#[aoc(day20, part2)]
|
|
#[allow(unused)]
|
|
fn part2(input: &str) -> u128 {
|
|
let mut machine = Machine::from(input.lines());
|
|
// println!("STATES: {}", machine.state_space());
|
|
// Find the rx module and look at its parent(s)
|
|
let rx = &machine.modules["rx"];
|
|
// my input has a single conjunction as parent, todo implement other possibilities
|
|
let con = &machine.modules[&rx.inputs[0]];
|
|
|
|
// for each input, find how long it takes for it to be High, so the conjunction sends a low to rx
|
|
let mut cycles: Vec<_> = Vec::new();
|
|
for input in con.inputs.clone() {
|
|
// print!("searching distance to {}...", input);
|
|
machine.reset();
|
|
let mut button_count = 0;
|
|
loop {
|
|
machine.press_button();
|
|
button_count += 1;
|
|
if let Some(distance) = machine.time_to_state(&input, PulseType::High) {
|
|
// println!("got {} pulses, {} button presses", distance, button_count);
|
|
cycles.push(button_count as u128);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
cycles.iter().fold(1, |accum, cycle| lcm(accum, *cycle))
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
const EXAMPLE: &str = "broadcaster -> a
|
|
%a -> inv, con
|
|
&inv -> b
|
|
%b -> con
|
|
&con -> output";
|
|
|
|
#[test]
|
|
fn part1_example() {
|
|
assert_eq!(part1(EXAMPLE), 11687500);
|
|
}
|
|
}
|