use std::fs; fn first_puzzle(input: &String) { // Go through each line and subtract it to the previous one, keeping only the positive results // and counting them, knowing that the first diff is invalid. let count = input.lines().scan(0, |current, line| { let previous = *current; *current = line.parse::().unwrap(); Some(*current - previous)}).filter(|diff| diff.is_positive()).count() - 1; println!("Count of single increases : {}", count); } 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(); sliding_window[3] = place + 1; if sliding_window[3] < 3 { Some(-1) } 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; println!("Count of triple sums increasing : {}", count); } fn main() { let contents = fs::read_to_string("../input.txt").expect("Could not open file."); first_puzzle(&contents); second_puzzle(&contents); 0; }