From 8baab634b6e7b131af78ee06036a8ddc4e9a6e22 Mon Sep 17 00:00:00 2001 From: omagdy7 Date: Sat, 9 Dec 2023 18:46:28 +0200 Subject: Day 9 done. --- 2023/Rust/src/day9.rs | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 2023/Rust/src/day9.rs (limited to '2023/Rust/src/day9.rs') diff --git a/2023/Rust/src/day9.rs b/2023/Rust/src/day9.rs new file mode 100644 index 0000000..ed8d63e --- /dev/null +++ b/2023/Rust/src/day9.rs @@ -0,0 +1,83 @@ +type History = Vec; + +#[derive(Debug)] +struct Report { + histories: Vec, +} + +impl From<&str> for Report { + fn from(report: &str) -> Self { + Self { + histories: report + .lines() + .map(|line| { + line.split_whitespace() + .map(|num| num.parse::().unwrap()) + .collect::() + }) + .collect::>(), + } + } +} + +fn solve_part_one(data: &str) -> u64 { + let report = Report::from(data); + let mut ans = 0; + for history in report.histories.iter() { + let mut differences = vec![]; + differences.push(history.clone()); + while !differences.last().unwrap().iter().all(|&x| x == 0) { + differences.push( + differences + .last() + .unwrap() + .windows(2) + .map(|window| window[1] - window[0]) + .collect::>(), + ) + } + + for i in (0..differences.len() - 2).rev() { + let last_last = differences[i + 1].last().unwrap() + differences[i].last().unwrap(); + differences[i].push(last_last); + } + ans += differences.first().unwrap().last().unwrap(); + } + ans as u64 +} + +fn solve_part_two(data: &str) -> u64 { + let report = Report::from(data); + let mut ans = 0; + for history in report.histories.iter() { + let mut differences = vec![]; + differences.push(history.clone()); + while !differences.last().unwrap().iter().all(|&x| x == 0) { + differences.push( + differences + .last() + .unwrap() + .windows(2) + .map(|window| window[1] - window[0]) + .collect::>(), + ) + } + + for i in (0..differences.len() - 2).rev() { + let first_first = differences[i].first().unwrap() - differences[i + 1].first().unwrap(); + differences[i].insert(0, first_first); + } + ans += differences.first().unwrap().first().unwrap(); + } + ans as u64 +} + +fn main() { + let test_1 = include_str!("../input/day9_1.test"); + let test_2 = include_str!("../input/day9_2.test"); + let prod = include_str!("../input/day9.prod"); + println!("part_1 test: {:?}", solve_part_one(test_1)); + println!("part_1 prod {:?}", solve_part_one(prod)); + println!("part_2 test: {:?}", solve_part_two(test_2)); + println!("part_2 prod {:?}", solve_part_two(prod)); +} -- cgit v1.2.3