From d94a6b3e6012b34db9470639d95a8223e4275cc5 Mon Sep 17 00:00:00 2001 From: dobiadi Date: Sat, 9 Dec 2023 22:19:40 +0100 Subject: [PATCH] Day9 Rust --- day9/rust/.gitignore | 1 + day9/rust/Cargo.lock | 7 +++++++ day9/rust/Cargo.toml | 8 ++++++++ day9/rust/src/main.rs | 37 +++++++++++++++++++++++++++++++++++++ 4 files changed, 53 insertions(+) create mode 100644 day9/rust/.gitignore create mode 100644 day9/rust/Cargo.lock create mode 100644 day9/rust/Cargo.toml create mode 100644 day9/rust/src/main.rs diff --git a/day9/rust/.gitignore b/day9/rust/.gitignore new file mode 100644 index 0000000..eb5a316 --- /dev/null +++ b/day9/rust/.gitignore @@ -0,0 +1 @@ +target diff --git a/day9/rust/Cargo.lock b/day9/rust/Cargo.lock new file mode 100644 index 0000000..b21cc6a --- /dev/null +++ b/day9/rust/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "rust" +version = "0.1.0" diff --git a/day9/rust/Cargo.toml b/day9/rust/Cargo.toml new file mode 100644 index 0000000..1ec6963 --- /dev/null +++ b/day9/rust/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "rust" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/day9/rust/src/main.rs b/day9/rust/src/main.rs new file mode 100644 index 0000000..f07ed10 --- /dev/null +++ b/day9/rust/src/main.rs @@ -0,0 +1,37 @@ +enum Direction { + Forward, + Backward, +} + +fn main() { + let stdin = std::io::stdin(); + + let mut part1 = 0; + let mut part2 = 0; + + for line in stdin.lines() { + let line = line.unwrap(); + + let history = line.split(" ").map(|e| e.parse().unwrap()).collect(); + + part1 += extrapolate(&history, Direction::Forward); + part2 += extrapolate(&history, Direction::Backward); + } + + println!("{}", part1); + println!("{}", part2); +} + +fn extrapolate(history: &Vec, direction: Direction) -> isize { + if history.iter().all(|e| *e == 0) { + return 0; + } + + let new_history = history.windows(2).map(|pair| pair[1] - pair[0]).collect(); + + if let Direction::Forward = direction { + return history.last().unwrap() + extrapolate(&new_history, direction); + } + + return history[0] - extrapolate(&new_history, direction); +}