day9: problem 2 solution

This commit is contained in:
Keenan Tims 2023-12-08 21:39:45 -08:00
parent d2718db633
commit 37b645c341
Signed by: ktims
GPG Key ID: 11230674D69038D4

View File

@ -56,6 +56,15 @@ impl History {
self.0[upper].push(new_value); 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 // PROBLEM 1 solution
@ -71,8 +80,14 @@ fn problem1<T: BufRead>(input: Lines<T>) -> i64 {
} }
// PROBLEM 2 solution // PROBLEM 2 solution
fn problem2<T: BufRead>(input: Lines<T>) -> u64 { fn problem2<T: BufRead>(input: Lines<T>) -> i64 {
0 let mut histories: Vec<History> = 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)] #[cfg(test)]
@ -93,6 +108,6 @@ mod tests {
#[test] #[test]
fn problem2_example() { fn problem2_example() {
let c = Cursor::new(EXAMPLE); let c = Cursor::new(EXAMPLE);
assert_eq!(problem2(c.lines()), 0); assert_eq!(problem2(c.lines()), 2);
} }
} }