aoc/year2021/day01.rs
1//! # Sonar Sweep
2//!
3//! The built in [`windows`] method comes in handy for this solution. For part 1 a straightforward
4//! sliding window of size 2 allows us to compare each 2 consecutive values.
5//!
6//! For part 2 we can use a trick to simplify. If we consider the first 2 windows of 3 elements
7//! each:
8//!
9//! ```none
10//! A1 A2 A3
11//! B1 B2 B3
12//! ```
13//!
14//! then the middle 2 elements are always in common, so the subsequent window is greater only
15//! if the last element is greater than the first. This means we can pick a sliding window of
16//! size 4 and compare the first and last elements, without having to sum intermediate elements.
17//!
18//! [`windows`]: slice::windows
19use crate::util::parse::*;
20
21pub fn parse(input: &str) -> Vec<u32> {
22 input.iter_unsigned().collect()
23}
24
25pub fn part1(input: &[u32]) -> usize {
26 input.windows(2).filter(|w| w[0] < w[1]).count()
27}
28
29pub fn part2(input: &[u32]) -> usize {
30 input.windows(4).filter(|w| w[0] < w[3]).count()
31}