diff --git a/2024/day-1/src/part1.rs b/2024/day-1/src/part1.rs index c004fc1..afb8e9d 100644 --- a/2024/day-1/src/part1.rs +++ b/2024/day-1/src/part1.rs @@ -1,6 +1,6 @@ #![warn(clippy::all, clippy::pedantic)] -use error_stack::Result; +use error_stack::{Report, Result, ResultExt}; use nom::{character::complete, multi::separated_list1, sequence::separated_pair, IResult}; use thiserror::Error; @@ -12,15 +12,16 @@ pub enum Day1Part1Error { } pub fn part1(input: &str) -> Result { - let (_, (mut col1, mut col2)) = - parse_input(input).expect("there should always be valid input from aoc"); - col1.sort(); - col2.sort(); + let (_, (mut col1, mut col2)) = parse_input(input) + .map_err(|x| Report::from(x.to_owned())) + .change_context(Day1Part1Error::ParseError)?; + col1.sort_unstable(); + col2.sort_unstable(); Ok(col1 .into_iter() .zip(col2.iter()) - .map(|(a, b)| u64::max(a, *b) - u64::min(a, *b)) + .map(|(a, b)| u64::abs_diff(a, *b)) .sum()) } @@ -30,7 +31,6 @@ fn parse_input(input: &str) -> IResult<&str, (Vec, Vec)> { separated_pair(complete::u64, complete::space1, complete::u64), )(input)?; Ok((input, combo.into_iter().unzip())) - } #[cfg(test)] @@ -51,4 +51,3 @@ mod test { assert_eq!(result, 11); } } - diff --git a/2024/day-1/src/part2.rs b/2024/day-1/src/part2.rs index f8de359..1664e94 100644 --- a/2024/day-1/src/part2.rs +++ b/2024/day-1/src/part2.rs @@ -11,6 +11,8 @@ use thiserror::Error; pub enum Day1Part2Error { #[error("Problem parsing Day 1")] ParseError, + #[error("Catastophic error")] + FatalError, } pub fn part2(input: &str) -> Result { @@ -22,7 +24,10 @@ pub fn part2(input: &str) -> Result { *val += 1; acc }); - Ok(col1.iter().map(|x| *x * col2_bucket.get(x).or(Some(&0)).unwrap()).sum()) + Ok(col1 + .iter() + .map(|x| *x * col2_bucket.get(x).unwrap_or(&0)) + .sum()) } fn parse_input(input: &str) -> IResult<&str, (Vec, Vec)> { @@ -51,4 +56,3 @@ mod test { assert_eq!(result, 31); } } -