From 37b645c3410ae82beb846fb2a55e0f666f05a01e Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Fri, 8 Dec 2023 21:39:45 -0800 Subject: [PATCH] day9: problem 2 solution --- 9/src/main.rs | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/9/src/main.rs b/9/src/main.rs index afe0da4..3f729f6 100644 --- a/9/src/main.rs +++ b/9/src/main.rs @@ -56,6 +56,15 @@ impl History { self.0[upper].push(new_value); } } + + fn extrapolate2(&mut self) { + self.build(); + self.0.last_mut().unwrap().insert(0, 0); + for (lower, upper) in (0..self.0.len()).rev().tuple_windows() { + let new_value = self.0[upper].first().unwrap() - self.0[lower].first().unwrap(); + self.0[upper].insert(0, new_value); + } + } } // PROBLEM 1 solution @@ -71,8 +80,14 @@ fn problem1(input: Lines) -> i64 { } // PROBLEM 2 solution -fn problem2(input: Lines) -> u64 { - 0 +fn problem2(input: Lines) -> i64 { + let mut histories: Vec = input.map(|s| History::from(s.unwrap().as_str())).collect(); + + for history in &mut histories { + history.extrapolate2(); + } + + histories.iter().map(|history| history.0.first().unwrap().first().unwrap()).sum() } #[cfg(test)] @@ -93,6 +108,6 @@ mod tests { #[test] fn problem2_example() { let c = Cursor::new(EXAMPLE); - assert_eq!(problem2(c.lines()), 0); + assert_eq!(problem2(c.lines()), 2); } }