diff --git a/aoc2021/src/day01.rs b/aoc2021/src/day01.rs index 26f40b3..13d369a 100644 --- a/aoc2021/src/day01.rs +++ b/aoc2021/src/day01.rs @@ -19,7 +19,19 @@ fn part1(input: &str) -> Result { .map(|line| line.parse::().map_err(anyhow::Error::new)) .collect::>>()?; - Ok(measurements.windows(2).filter(|w| w[0] < w[1]).count()) + Ok(count_increases(measurements.iter())) +} + +fn count_increases(numbers: I) -> usize +where + C: std::cmp::PartialOrd, + I: Iterator + Clone, +{ + numbers + .clone() + .zip(numbers.skip(1)) + .filter(|(a, b)| a < b) + .count() } fn part2(input: &str) -> Result { @@ -28,20 +40,9 @@ fn part2(input: &str) -> Result { .map(|line| line.parse::().map_err(anyhow::Error::new)) .collect::>>()?; - let mut increases = 0; - let mut prev: Option = None; - - for window in measurements.windows(3) { - let sum = window.iter().sum(); - if let Some(prev) = prev { - if prev < sum { - increases += 1; - } - } - prev = Some(sum); - } - - Ok(increases) + Ok(count_increases( + measurements.windows(3).map(|w| w.iter().sum::()), + )) } #[cfg(test)]