Added comments for Day 1 2021

This commit is contained in:
Teo-CD 2021-12-04 00:08:34 +00:00
parent 4f147f4f7a
commit 218321e6ae

View file

@ -12,6 +12,8 @@ fn first_puzzle(input: &String) {
} }
fn second_puzzle(input: &String) { fn second_puzzle(input: &String) {
// For each input, add it to a circular buffer whose write position is stored at the end.
// For all but the first two elements, output the sum of the circular buffer.
let count = input.lines().scan([0; 4], |sliding_window: &mut [i32; 4], line|{ let count = input.lines().scan([0; 4], |sliding_window: &mut [i32; 4], line|{
let place = sliding_window[3]; let place = sliding_window[3];
sliding_window[(place % 3) as usize] = line.parse::<i32>().unwrap(); sliding_window[(place % 3) as usize] = line.parse::<i32>().unwrap();
@ -22,7 +24,9 @@ fn second_puzzle(input: &String) {
} else { } else {
Some(sliding_window[0..3].iter().sum::<i32>()) Some(sliding_window[0..3].iter().sum::<i32>())
} }
// Filter out the first two elements, can't generate a three-element sum.
}).filter(|sum| !sum.is_negative()).scan(0, |current, sum| { }).filter(|sum| !sum.is_negative()).scan(0, |current, sum| {
// Subtract each successive elements, similarly to the first solution.
let previous = *current; let previous = *current;
*current = sum; *current = sum;
Some(*current - previous)}).filter(|diff| diff.is_positive()).count() - 1; Some(*current - previous)}).filter(|diff| diff.is_positive()).count() - 1;