From 61d540ed868dbb91167cb3e9eb8108342104ffb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leon=20Gr=C3=BCnewald?= <10533763+dhalucario@users.noreply.github.com> Date: Thu, 12 Dec 2024 22:12:49 +0100 Subject: [PATCH] Update to also do part 2 --- 5/src/main.rs | 45 +++++++++++++++++++++++++++++++++------------ 1 file changed, 33 insertions(+), 12 deletions(-) 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(()) }