diff --git a/5/src/main.rs b/5/src/main.rs index 254a9e3..b745fa7 100644 --- a/5/src/main.rs +++ b/5/src/main.rs @@ -57,27 +57,48 @@ fn sum_middle_page_nums(updates: Vec>) -> i64 { .sum() } +fn correct_update(update: &mut Vec<&str>, before_index: usize) { + let elem = update.remove(before_index); + update.insert(0, elem); +} + fn main() -> anyhow::Result<()> { let data = get_data()?; let (rules, updates) = parse_rules_and_updates(&data); let mut correct_updates = Vec::new(); + let mut corrected_updates = Vec::new(); - 'update: for update in updates { - for rule in &rules { - if let Some(_) = check_rule_compliance(&update, rule) { - /*println!( - "Rule issue: {:?} ({before_index:?}) {:?} ({after_index:?})", - update[before_index], - update[after_index] - ); - println!("Elements: {update:?}");*/ - continue 'update; + 'update: for mut update in updates { + let mut fixed = false; + let mut keep_fixing = true; + + while keep_fixing { + keep_fixing = false; + for rule in &rules { + if let Some((before_index, after_index)) = check_rule_compliance(&update, rule) { + fixed = true; + keep_fixing = true; + println!("Elements: {update:?}"); + println!( + "Rule issue: {:?} ({before_index:?}) {:?} ({after_index:?})", + update[before_index], + update[after_index] + ); + correct_update(&mut update, before_index); + println!("Elements: {update:?}"); + } } } - correct_updates.push(update); + + if fixed { + corrected_updates.push(update); + } else { + correct_updates.push(update); + } } - + println!("{}", sum_middle_page_nums(correct_updates)); + println!("{}", sum_middle_page_nums(corrected_updates)); Ok(()) }