Day 1: Sonar Sweep
Part 1 asks to find when the current depth is greater than the previous depth. Part 2 asks to find when the current running sum of depths is greater than the previous running sum, with a running sum of length 3. These are both special cases of finding when the current length- running sum of depths is greater than the previous length- running sum, with Part 1 using a length of and Part 2 using .
The solution uses a CircularBuffer
to keep the past depths.
Since the “interior” components of the current and previous running sums are the same, we can compare the two running sums by merely checking the incoming number against the outgoing number, i.e., the new depth against the oldest depth still in the buffer.
If the current depth is greater, then so is the current running sum.
Setup
use crate::Answer;
use std::collections::VecDeque;
fn get_n_increasing_running_sum_of_depths(input: &str, n: usize) -> Option<usize> {
let mut depth_buf = VecDeque::with_capacity(n);
let mut depths = input.lines().map(|line| line.parse::<i32>().unwrap());
depth_buf.extend(depths.by_ref().take(n));
if depth_buf.len() < n {
return None;
}
let mut n_increasing = 0;
for new_depth in depths {
let old_depth = depth_buf.pop_front().unwrap();
depth_buf.push_back(new_depth);
if new_depth > old_depth {
n_increasing += 1;
}
}
Some(n_increasing)
}
fn ans_for_input(input: &str) -> Answer<usize, usize> {
(1, (pt1(input), pt2(input))).into()
}
pub fn ans() -> Answer<usize, usize> {
ans_for_input(include_str!("input.txt"))
}