Day9 Rust

This commit is contained in:
dobiadi
2023-12-09 22:19:40 +01:00
parent 7655698056
commit d94a6b3e60
4 changed files with 53 additions and 0 deletions

1
day9/rust/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
target

7
day9/rust/Cargo.lock generated Normal file
View File

@@ -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"

8
day9/rust/Cargo.toml Normal file
View File

@@ -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]

37
day9/rust/src/main.rs Normal file
View File

@@ -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<isize>, 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);
}