Day9 Rust
This commit is contained in:
1
day9/rust/.gitignore
vendored
Normal file
1
day9/rust/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
target
|
||||
7
day9/rust/Cargo.lock
generated
Normal file
7
day9/rust/Cargo.lock
generated
Normal 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
8
day9/rust/Cargo.toml
Normal 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
37
day9/rust/src/main.rs
Normal 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);
|
||||
}
|
||||
Reference in New Issue
Block a user