From 5b2760e9f7f396e981734fab5c84a253359cbab5 Mon Sep 17 00:00:00 2001 From: Andrew Coleman Date: Sun, 10 Dec 2023 14:57:00 -0500 Subject: [PATCH] day9 solution --- 2023/src/day09.rs | 75 +++++++++++++++++++++++++++++++++++++++++++++++ 2023/src/lib.rs | 1 + 2 files changed, 76 insertions(+) create mode 100644 2023/src/day09.rs diff --git a/2023/src/day09.rs b/2023/src/day09.rs new file mode 100644 index 0000000..4164459 --- /dev/null +++ b/2023/src/day09.rs @@ -0,0 +1,75 @@ +use aoc_runner_derive::{aoc, aoc_generator}; + +type Seq = Vec; + +fn all_zero(s: &Seq) -> bool { + s.iter().find(|t| **t != 0).is_none() +} + +#[aoc_generator(day9)] +fn parse(input: &str) -> Vec { + input + .lines() + .filter_map(|line| { + if !line.is_empty() { + let nums = line.split(" ").map(|n| n.parse::().unwrap()).collect(); + Some(nums) + } else { + None + } + }) + .collect() +} + +fn get_diffs(s: &Seq) -> Seq { + let mut result: Seq = vec![]; + for index in 0..(s.len() - 1) { + result.push(s[index + 1] - s[index]); + } + result +} + +fn next_number(s: &Seq) -> i64 { + if all_zero(s) { + 0 + } else { + let d = get_diffs(s); + s.last().unwrap() + next_number(&d) + } +} + +#[aoc(day9, part1)] +fn part1(input: &[Seq]) -> i64 { + input.iter().map(|s| next_number(&s)).sum() +} + +fn previous_number(s: &Seq) -> i64 { + if all_zero(s) { + 0 + } else { + let d = get_diffs(s); + s[0] - previous_number(&d) + } +} + +#[aoc(day9, part2)] +fn part2(input: &[Seq]) -> i64 { + input.iter().map(|s| previous_number(&s)).sum() +} + +#[cfg(test)] +mod tests { + use super::*; + + const SAMPLE_DATA: &'static str = r#"0 3 6 9 12 15 +1 3 6 10 15 21 +10 13 16 21 30 45 +"#; + + #[test] + fn sample_data() { + let input = parse(&SAMPLE_DATA); + assert_eq!(part1(&input), 114); + assert_eq!(part2(&input), 2); + } +} diff --git a/2023/src/lib.rs b/2023/src/lib.rs index 4d0316e..63c5ba7 100644 --- a/2023/src/lib.rs +++ b/2023/src/lib.rs @@ -8,5 +8,6 @@ mod day05; mod day06; mod day07; mod day08; +mod day09; aoc_lib! { year = 2023 }