diff --git a/2021/Day 1/rust_solution/src/main.rs b/2021/Day 1/rust_solution/src/main.rs index 4222670..2806a66 100644 --- a/2021/Day 1/rust_solution/src/main.rs +++ b/2021/Day 1/rust_solution/src/main.rs @@ -12,6 +12,8 @@ fn first_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 place = sliding_window[3]; sliding_window[(place % 3) as usize] = line.parse::().unwrap(); @@ -22,7 +24,9 @@ fn second_puzzle(input: &String) { } else { Some(sliding_window[0..3].iter().sum::()) } + // Filter out the first two elements, can't generate a three-element sum. }).filter(|sum| !sum.is_negative()).scan(0, |current, sum| { + // Subtract each successive elements, similarly to the first solution. let previous = *current; *current = sum; Some(*current - previous)}).filter(|diff| diff.is_positive()).count() - 1;