From 7f166a5075c8cc08af9e405002a31f9757f782f5 Mon Sep 17 00:00:00 2001 From: Wesley Moore Date: Sat, 9 Dec 2023 16:05:00 +1000 Subject: [PATCH] 2023: Day 9, part 2 --- 2023/day9/src/main.rs | 46 ++++++++++++++++++++++++++++++++----------- 1 file changed, 34 insertions(+), 12 deletions(-) diff --git a/2023/day9/src/main.rs b/2023/day9/src/main.rs index 04ff99c..9737598 100644 --- a/2023/day9/src/main.rs +++ b/2023/day9/src/main.rs @@ -11,15 +11,19 @@ fn main() -> Result<(), BoxError> { .next() .ok_or("missing input file path")?; let file = BufReader::new(File::open(input_path)?); - let mut sum = 0; + let mut part1 = 0; + let mut part2 = 0; for line in file.lines() { let line = line?; let history = parse_line(&line)?; let value = calculate_next_value(&history); - sum += value; + let prev_value = calculate_prev_value(&history); + part1 += value; + part2 += prev_value; } - println!("Part 1: {sum}"); + println!("Part 1: {part1}"); + println!("Part 2: {part2}"); Ok(()) } @@ -31,15 +35,7 @@ fn parse_line(line: &str) -> Result, ParseIntError> { } fn calculate_next_value(history: &[i32]) -> i32 { - let x: Vec<_> = history - .windows(2) - .map(|window| { - let &[a, b] = window else { - unreachable!("window is not a pair") - }; - b - a - }) - .collect(); + let x = window_differences(history); // See if they're all the same, if so then the next value is the same let first = x[0]; @@ -50,3 +46,29 @@ fn calculate_next_value(history: &[i32]) -> i32 { calculate_next_value(&x) } } + +fn calculate_prev_value(history: &[i32]) -> i32 { + let x = window_differences(history); + + // See if they're all the same, if so then the next value is the same + let same = x[0]; + let first = history.first().unwrap(); + first + - if x.iter().all(|val| *val == same) { + same + } else { + calculate_prev_value(&x) + } +} + +fn window_differences(values: &[i32]) -> Vec { + values + .windows(2) + .map(|window| { + let &[a, b] = window else { + unreachable!("window is not a pair") + }; + b - a + }) + .collect() +}