From e520c93ccde856b3cf045c7d888a9615fc1d2833 Mon Sep 17 00:00:00 2001 From: Drew Galbraith Date: Tue, 19 Dec 2023 12:37:47 -0800 Subject: [PATCH] Apply some basic reductions to the state machine for fun in day19 --- src/day19.rs | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/src/day19.rs b/src/day19.rs index 5284c43..1055ca4 100644 --- a/src/day19.rs +++ b/src/day19.rs @@ -8,7 +8,7 @@ enum Test { Default, } -#[derive(PartialEq, Debug)] +#[derive(PartialEq, Debug, Copy, Clone)] enum Action<'a> { GoTo(&'a str), Accept, @@ -190,6 +190,41 @@ fn calc_possibilities(machine: &HashMap<&str, Vec>) -> u64 { calc_remaining_possibilites(machine, insteps, &mut Vec::new()) } +fn reduce_steps(steps: &mut Vec) { + let default_step = steps.pop().unwrap(); + while steps.len() > 0 && steps.last().unwrap().action == default_step.action { + steps.pop(); + } + steps.push(default_step); +} + +fn reduce_machine(machine: &mut HashMap<&str, Vec>) { + loop { + let mut singles: Vec<&str> = Vec::new(); + for (k, v) in &mut *machine { + reduce_steps(v); + if v.len() == 1 { + singles.push(k); + } + } + + if singles.len() == 0 { + return; + } + + for single in singles { + let a: Action = machine.remove(single).unwrap().first().unwrap().action; + for v in machine.values_mut() { + for step in v { + if step.action == Action::GoTo(single) { + step.action = a; + } + } + } + } + } +} + pub fn sum_accepted() -> (u64, u64) { let mut buffer = String::new(); @@ -205,5 +240,7 @@ pub fn sum_accepted() -> (u64, u64) { let inputs = inputs.split("\n").map(parse_inputs).collect(); + reduce_machine(&mut machine); + (calc_sum(&machine, &inputs), calc_possibilities(&machine)) }