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-nn running sum of depths is greater than the previous length-nn running sum, with Part 1 using a length of n=1n=1 and Part 2 using n=3n=3.

The solution uses a CircularBuffer to keep the past nn 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"))
}

Parts 1 and 2

fn pt1(input: &str) -> usize {
	get_n_increasing_running_sum_of_depths(input, 1).unwrap()
}
fn pt2(input: &str) -> usize {
	get_n_increasing_running_sum_of_depths(input, 3).unwrap()
}

This page was built using Antora with a theme forked from the default UI. Search is powered by Lunr.

The source code for this UI is licensed under the terms of the MPL-2.0 license.