diff --git a/bin/src/main.rs b/bin/src/main.rs index a805219..86271f0 100644 --- a/bin/src/main.rs +++ b/bin/src/main.rs @@ -105,12 +105,12 @@ fn day_6() { println!("# Day 6"); let input = get_input!("day6"); - let races = Races::from_multiple_races(&input); + let races = Races::from_multiple_races(&input).expect("Failed to parse races"); let winning_product = races.get_winning_product(); println!("Winning product for multiple races: {winning_product}"); - let race = Races::from_single_race(&input); + let race = Races::from_single_race(&input).expect("Failed to parse race"); let winning_product = race.get_winning_product(); println!("Winning product for single race: {winning_product}"); diff --git a/lib/boat_race/src/lib.rs b/lib/boat_race/src/lib.rs index 5e8a400..7f88417 100644 --- a/lib/boat_race/src/lib.rs +++ b/lib/boat_race/src/lib.rs @@ -1,5 +1,11 @@ use std::num::ParseIntError; +#[derive(Debug)] +pub enum ParseRaceError { + ParseInt(ParseIntError), + Invalid(String), +} + pub struct Race { time: u64, distance: u64, @@ -64,38 +70,37 @@ impl Races { self.races.iter().map(Race::find_winning_conditions_amount).product() } - pub fn from_single_race(races: &str) -> Self { + pub fn from_single_race(races: &str) -> Result { let numbers = races .lines() .map(|line| { line.split(':') .last() - .expect("Failed to get numbers") + .ok_or_else(|| ParseRaceError::Invalid("Failed to get numbers".to_string()))? .split_ascii_whitespace() .collect::() .parse::() - .expect("Failed to parse number") + .map_err(ParseRaceError::ParseInt) }) - .collect::>(); + .collect::, ParseRaceError>>()?; let races = vec![Race::new(numbers[0], numbers[1])]; - Self { races } + Ok(Self { races }) } - pub fn from_multiple_races(races: &str) -> Self { + pub fn from_multiple_races(races: &str) -> Result { let numbers = races .lines() .map(|line| { line.split(':') .last() - .expect("Failed to get numbers") + .ok_or_else(|| ParseRaceError::Invalid("Failed to get numbers".to_string()))? .split_ascii_whitespace() - .map(|n| n.parse::()) - .collect::, ParseIntError>>() - .expect("Failed to parse numbers") + .map(|n| n.parse::().map_err(ParseRaceError::ParseInt)) + .collect::, ParseRaceError>>() }) - .collect::>>(); + .collect::>, ParseRaceError>>()?; let races = numbers[0] .iter() @@ -103,7 +108,7 @@ impl Races { .map(|x| Race::new(*x.0, *x.1)) .collect::>(); - Self { races } + Ok(Self { races }) } } @@ -116,13 +121,17 @@ Distance: 9 40 200"; #[test] fn solution_1() { - let product = Races::from_multiple_races(EXAMPLE).get_winning_product(); + let product = Races::from_multiple_races(EXAMPLE) + .expect("Failed to parse races") + .get_winning_product(); assert_eq!(product, 288) } #[test] fn solution_2() { - let product = Races::from_single_race(EXAMPLE).get_winning_product(); + let product = Races::from_single_race(EXAMPLE) + .expect("Failed to parse race") + .get_winning_product(); assert_eq!(product, 71503); } }