From 363ea1a0243c137b2480c421404e5124770ed09b Mon Sep 17 00:00:00 2001 From: Justin Wernick Date: Wed, 1 Dec 2021 10:13:48 +0200 Subject: Refactor out common code --- src/bin/day_1.rs | 49 +++++++++++++++++++++---------------------------- src/parsers.rs | 2 +- 2 files changed, 22 insertions(+), 29 deletions(-) diff --git a/src/bin/day_1.rs b/src/bin/day_1.rs index 7b89d69..ca2e242 100644 --- a/src/bin/day_1.rs +++ b/src/bin/day_1.rs @@ -6,35 +6,18 @@ fn main() -> Result<(), Box> { let input = fs::read_to_string("inputs/day_1.txt")?; let sonar_scan = parse_sonar_scan(&input).unwrap().1; - { - let mut simple_increase_counter = DepthIncreaseCounter::default(); - for (depth, next_depth) in sonar_scan.iter().zip(sonar_scan.iter().skip(1)) { - if next_depth > depth { - simple_increase_counter.increment(); - } - } - dbg!(simple_increase_counter); - } + let simple_increase_counter = count_increases(sonar_scan.iter()); + dbg!(simple_increase_counter); - { - let windowed_sonar_scan = sonar_scan - .iter() - .zip(sonar_scan.iter().skip(1)) - .zip(sonar_scan.iter().skip(2)) - .map(|((depth1, depth2), depth3)| ThreeDepthWindowSum::new([*depth1, *depth2, *depth3])) - .collect::>(); + let windowed_sonar_scan = sonar_scan + .iter() + .zip(sonar_scan.iter().skip(1)) + .zip(sonar_scan.iter().skip(2)) + .map(|((depth1, depth2), depth3)| ThreeDepthWindowSum::new([*depth1, *depth2, *depth3])) + .collect::>(); - let mut windowed_increase_counter = DepthIncreaseCounter::default(); - for (depth, next_depth) in windowed_sonar_scan - .iter() - .zip(windowed_sonar_scan.iter().skip(1)) - { - if next_depth > depth { - windowed_increase_counter.increment(); - } - } - dbg!(windowed_increase_counter); - } + let windowed_increase_counter = count_increases(windowed_sonar_scan.iter()); + dbg!(windowed_increase_counter); Ok(()) } @@ -56,7 +39,7 @@ fn parse_sonar_scan(input: &str) -> IResult<&str, Vec> { } fn parse_depth(input: &str) -> IResult<&str, Depth> { - map(parsers::u64, |number| Depth(number))(input) + map(parsers::u64, Depth)(input) } #[derive(Default, Debug)] @@ -68,6 +51,16 @@ impl DepthIncreaseCounter { } } +fn count_increases(i: impl IntoIterator + Clone) -> DepthIncreaseCounter { + let mut increases = DepthIncreaseCounter::default(); + for (depth, next_depth) in i.clone().into_iter().zip(i.into_iter().skip(1)) { + if next_depth > depth { + increases.increment(); + } + } + increases +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/parsers.rs b/src/parsers.rs index 27b2aad..c33a3cc 100644 --- a/src/parsers.rs +++ b/src/parsers.rs @@ -2,5 +2,5 @@ use nom::{character::complete::digit1, combinator::map_res, IResult}; use std::str::FromStr; pub fn u64(input: &str) -> IResult<&str, u64> { - map_res(digit1, |number| u64::from_str(number))(input) + map_res(digit1, u64::from_str)(input) } -- cgit v1.2.3