diff options
author | Justin Wernick <justin@worthe-it.co.za> | 2023-12-06 15:11:27 +0200 |
---|---|---|
committer | Justin Wernick <justin@worthe-it.co.za> | 2023-12-06 15:11:27 +0200 |
commit | 1f569f706122ac6605baa2286424f2529671329d (patch) | |
tree | b9c9feffc5cf29c10e3a8d799f8eb77898571b72 /2023/src | |
parent | 487eafd13f5d69fd29cdb9be35bfc399d93e52f3 (diff) |
Day 6
Diffstat (limited to '2023/src')
-rw-r--r-- | 2023/src/bin/day_6.rs | 67 |
1 files changed, 59 insertions, 8 deletions
diff --git a/2023/src/bin/day_6.rs b/2023/src/bin/day_6.rs index b3a610b..138843e 100644 --- a/2023/src/bin/day_6.rs +++ b/2023/src/bin/day_6.rs @@ -1,19 +1,70 @@ -use nom::IResult; +use nom::{ + bytes::complete::tag, + character::complete::{line_ending, space1, u64 as nom_u64}, + combinator::map, + multi::separated_list1, + sequence::tuple, + IResult, +}; use std::fs; fn main() -> Result<(), Box<dyn std::error::Error>> { - let input = fs::read_to_string("inputs/day_2.txt")?; - let parsed = Example::parser(&input).unwrap().1; - dbg!(&parsed); + let input = fs::read_to_string("inputs/day_6.txt")?; + let parsed = RacePlan::multi_parser(&input).unwrap().1; + for plan in parsed { + dbg!(&plan.win_count_product()); + } Ok(()) } #[derive(Debug)] -struct Example; +struct RacePlan(Vec<RaceRecord>); + +#[derive(Debug)] +struct RaceRecord { + time: u64, + distance: u64, +} + +impl RacePlan { + fn multi_parser(input: &str) -> IResult<&str, Vec<Self>> { + separated_list1(line_ending, RacePlan::parser)(input) + } + + fn parser(input: &str) -> IResult<&str, Self> { + map( + tuple(( + tag("Time:"), + space1, + separated_list1(space1, nom_u64), + line_ending, + tag("Distance:"), + space1, + separated_list1(space1, nom_u64), + )), + |(_, _, times, _, _, _, distances)| { + RacePlan( + times + .into_iter() + .zip(distances.into_iter()) + .map(|(time, distance)| RaceRecord { time, distance }) + .collect(), + ) + }, + )(input) + } + + fn win_count_product(&self) -> usize { + self.0.iter().map(|r| r.count_wins()).product() + } +} -impl Example { - fn parser(_input: &str) -> IResult<&str, Self> { - todo!() +impl RaceRecord { + fn count_wins(&self) -> usize { + (1..self.time) + .map(|charge_time| charge_time * (self.time - charge_time)) + .filter(|distance| *distance > self.distance) + .count() } } |