From ab9a4bde332376a0b35af473d56fda6dfbe49cea Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 9 Dec 2023 13:11:33 +0100 Subject: [PATCH] day(09): add solution Signed-off-by: Matej Focko --- samples/day09.txt | 3 +++ src/bin/day09.rs | 64 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 samples/day09.txt create mode 100644 src/bin/day09.rs diff --git a/samples/day09.txt b/samples/day09.txt new file mode 100644 index 0000000..539a763 --- /dev/null +++ b/samples/day09.txt @@ -0,0 +1,3 @@ +0 3 6 9 12 15 +1 3 6 10 15 21 +10 13 16 21 30 45 diff --git a/src/bin/day09.rs b/src/bin/day09.rs new file mode 100644 index 0000000..89df934 --- /dev/null +++ b/src/bin/day09.rs @@ -0,0 +1,64 @@ +use aoc_2023::*; + +type Output1 = i32; +type Output2 = Output1; + +struct Day09 { + values: Vec>, +} +impl Solution for Day09 { + fn new>(pathname: P) -> Self { + let values = file_to_lines::, P>(pathname) + .iter() + .map(|vals| parse_ws_separated(vals)) + .collect_vec(); + + Self { values } + } + + fn part_1(&mut self) -> Output1 { + self.values + .iter() + .map(|xs| { + let mut ds = vec![]; + + let mut last_row = xs.clone(); + while last_row.iter().any(|&x| x != 0) { + let next_row = last_row.windows(2).map(|s| s[1] - s[0]).collect_vec(); + + ds.push(*next_row.last().unwrap()); + last_row = next_row; + } + + xs.last().unwrap() + ds.iter().rev().sum::() + }) + .sum() + } + + fn part_2(&mut self) -> Output2 { + self.values + .iter() + .map(|xs| { + let mut ds = vec![]; + + let mut last_row = xs.clone(); + last_row.reverse(); + + while last_row.iter().any(|&x| x != 0) { + let next_row = last_row.windows(2).map(|s| s[1] - s[0]).collect_vec(); + + ds.push(*next_row.last().unwrap()); + last_row = next_row; + } + + xs.first().unwrap() + ds.iter().rev().sum::() + }) + .sum() + } +} + +fn main() -> Result<()> { + Day09::main() +} + +test_sample!(day_09, Day09, 114, 2);