Apply some basic reductions to the state machine for fun in day19
This commit is contained in:
parent
27bf55960a
commit
e520c93ccd
39
src/day19.rs
39
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<Step>>) -> u64 {
|
|||
calc_remaining_possibilites(machine, insteps, &mut Vec::new())
|
||||
}
|
||||
|
||||
fn reduce_steps(steps: &mut Vec<Step>) {
|
||||
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<Step>>) {
|
||||
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))
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue