use aoc_runner_derive::aoc; use itertools::Itertools; // PARSE #[derive(Debug)] struct History(Vec>); impl From<&str> for History { fn from(s: &str) -> Self { let hist: Vec = s.split_whitespace().map(|num| num.parse().unwrap()).collect(); Self(vec![hist]) } } impl History { fn build_row(&mut self) { let last = self.0.last().unwrap(); self.0.push(last.iter().tuple_windows().map(|(a, b)| b - a).collect()) } fn build(&mut self) { while !self.0.last().unwrap().iter().all(|x| *x == 0) { self.build_row(); } } fn extrapolate(&mut self) { self.build(); self.0.last_mut().unwrap().push(0); for (lower, upper) in (0..self.0.len()).rev().tuple_windows() { let new_value = self.0[upper].last().unwrap() + self.0[lower].last().unwrap(); 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 #[aoc(day9, part1)] fn part1(input: &str) -> i64 { let mut histories: Vec = input.lines().map(|s| History::from(s)).collect(); for history in &mut histories { history.extrapolate(); } histories .iter() .map(|history| history.0.first().unwrap().last().unwrap()) .sum() } // PROBLEM 2 solution #[aoc(day9, part2)] fn part2(input: &str) -> i64 { let mut histories: Vec = input.lines().map(|s| History::from(s)).collect(); for history in &mut histories { history.extrapolate2(); } histories .iter() .map(|history| history.0.first().unwrap().first().unwrap()) .sum() } #[cfg(test)] mod tests { use super::*; const EXAMPLE: &str = "0 3 6 9 12 15 1 3 6 10 15 21 10 13 16 21 30 45"; #[test] fn part1_example() { assert_eq!(part1(EXAMPLE), 114); } #[test] fn part2_example() { assert_eq!(part2(EXAMPLE), 2); } }