From da8b25b4e2bed8ce0e674d1991dfc15f7fa3d507 Mon Sep 17 00:00:00 2001 From: Sebastian Tobie Date: Thu, 19 Dec 2024 18:47:24 +0100 Subject: [PATCH] solved day 5 --- days/2024/05.rs | 87 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 days/2024/05.rs diff --git a/days/2024/05.rs b/days/2024/05.rs new file mode 100644 index 0000000..021e5dc --- /dev/null +++ b/days/2024/05.rs @@ -0,0 +1,87 @@ +use advent_of_code::strings::{convert_to_array, parsenumber}; +use advent_of_code_macros::include_aoc; +use log::*; +include_aoc!(DATA, 2024, 05, 2); + +fn correct_sum(updates: Vec>, orders: Vec<(u32, u32)>) -> u32 { + let mut correct_numbers = 0; + 'updateloop: for update in updates.clone().iter() { + for order in orders.clone() { + let (mut beforepos, mut afterpos) = (update.len(), update.len()); + for i in 0..update.len() { + if update[i] == order.0 { + beforepos = i + } else if update[i] == order.1 { + afterpos = i + } + } + if beforepos != update.len() && afterpos != update.len() { + if beforepos > afterpos { + continue 'updateloop; + } + } + } + let centerpos = if update.len() % 2 == 1 { + (update.len() - 1) / 2 + } else { + update.len() / 2 + }; + debug!("Adding {}: {:?}", update[centerpos], update); + correct_numbers += update[centerpos] + } + correct_numbers +} + +fn incorrect_sum(updates: Vec>, orders: Vec<(u32, u32)>) -> u32 { + let mut numbers = 0; + 'updateloop: for update in updates.clone().iter_mut() { + let mut broken; + let mut was_broken = false; + loop { + broken = false; + for order in orders.clone() { + let (mut beforepos, mut afterpos) = (update.len(), update.len()); + for i in 0..update.len() { + if update[i] == order.0 { + beforepos = i + } else if update[i] == order.1 { + afterpos = i + } + } + if beforepos != update.len() && afterpos != update.len() { + if beforepos > afterpos { + (update[beforepos], update[afterpos]) = (update[afterpos], update[beforepos]); + debug!("switching {} with {} in {:?}", update[beforepos], update[afterpos], update); + broken = true; + was_broken = true; + } + } + } + if !was_broken { + continue 'updateloop; + } + if !broken { + break; + } + } + + let centerpos = if update.len() % 2 == 1 { + (update.len() - 1) / 2 + } else { + update.len() / 2 + }; + debug!("Adding {}: {:?}", update[centerpos], update); + numbers += update[centerpos] + } + numbers +} + +fn main() { + let update_order = convert_to_array::<_, _, '\n'>(DATA_1, |l| { + let x = l.split_once('|').unwrap(); + (parsenumber(x.0), parsenumber(x.1)) + }); + let updates: Vec> = convert_to_array::<_, _, '\n'>(DATA_2, |line| line.split(',').map(parsenumber).collect()); + println!("The Sum of the center of the correct numbers are {}", correct_sum(updates.clone(), update_order.clone())); + println!("The Sum of the center of the incorrect numbers are {}", incorrect_sum(updates.clone(), update_order.clone())); +}