diff --git a/src/solutions/day_5.rs b/src/solutions/day_5.rs index 96f01f9..831da70 100644 --- a/src/solutions/day_5.rs +++ b/src/solutions/day_5.rs @@ -58,18 +58,43 @@ pub fn run(mut args: env::Args) -> std::io::Result<()> { } } - lists.retain(|v| is_compliant(v, &ordering)); - // Task 1 - let sum = lists.iter().fold(0, |acc, v| { - let idx = v.len().div_floor(2); - acc + v[idx] as u32 - }); + let sum = lists + .iter() + .filter(|v| is_compliant(v, &ordering)) + .fold(0, |acc, v| { + let idx = v.len().div_floor(2); + acc + v[idx] as u32 + }); println!("Sum of middle values: {sum}"); // Task 2 - // TBD + let sum_fixed = lists + .into_iter() + .filter(|v| !is_compliant(v, &ordering)) + .map(|mut v| { + v.sort_unstable_by(|this, other| { + if let Some(entry) = ordering.get(this) { + if entry.less_than.contains(&other) { + std::cmp::Ordering::Less + } else if entry.greater_than.contains(&other) { + std::cmp::Ordering::Greater + } else { + std::cmp::Ordering::Less + } + } else { + std::cmp::Ordering::Less + } + }); + v + }) + .fold(0, |acc, v| { + let idx = v.len().div_floor(2); + acc + v[idx] as u32 + }); + + println!("Sum of corrected middle values: {sum_fixed}"); Ok(()) } @@ -89,3 +114,4 @@ fn is_compliant(list: &[u8], ordering: &HashMap) -> bool { return true; } +