Added day 2 code for part 1 and 2

Signed-off-by: Louis Vallat <louis@louis-vallat.xyz>
This commit is contained in:
Louis Vallat 2021-12-03 21:48:01 +01:00
parent c73c41bf4c
commit f420e96477
No known key found for this signature in database
GPG Key ID: 0C87282F76E61283
3 changed files with 1065 additions and 0 deletions

8
day2/Cargo.toml Normal file
View File

@ -0,0 +1,8 @@
[package]
name = "day2"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

1000
day2/input Normal file

File diff suppressed because it is too large Load Diff

57
day2/src/main.rs Normal file
View File

@ -0,0 +1,57 @@
use std::{fs, env, vec};
fn read_input(path: &str) -> String {
return fs::read_to_string(path).expect("Cannot read file.");
}
fn parse_input(s: &str) -> Vec<(String, i32)> {
let mut r:Vec<(String, i32)> = vec![];
let v = s.split("\n").into_iter();
for e in v {
let p = e.split_whitespace().collect::<Vec<&str>>();
if p.len() == 2 && p[1].parse::<i32>().is_ok() {
r.push((p[0].to_owned(), p[1].parse::<i32>().unwrap()));
}
}
return r;
}
fn compute_horizontal_depth_aim(t: (String, i32), a: (i32, i32, i32)) -> (i32, i32, i32) {
return match t.0.as_str() {
"up" => (a.0, a.1, a.2 - t.1),
"down" => (a.0, a.1, a.2 + t.1),
"forward" => (a.0 + t.1, a.1 + a.2 * t.1, a.2),
_ => a
};
}
fn compute_horizontal_depth(t: (String, i32), a: (i32, i32)) -> (i32, i32) {
return match t.0.as_str() {
"up" => (a.0, a.1 - t.1),
"down" => (a.0, a.1 + t.1),
"forward" => (a.0 + t.1, a.1),
_ => a
};
}
fn get_horizontal_depth_aim(v: Vec<(String, i32)>) -> (i32, i32, i32) {
return v.into_iter().fold((0, 0, 0), |acc, e| compute_horizontal_depth_aim(e, acc));
}
fn get_horizontal_depth(v: Vec<(String, i32)>) -> (i32, i32) {
return v.into_iter().fold((0, 0), |acc, e| compute_horizontal_depth(e, acc));
}
fn main() {
let args: Vec<String> = env::args().collect();
for arg in args.iter().skip(1) {
let v = parse_input(&read_input(&arg));
let r1 = get_horizontal_depth(v.clone());
let r2 = get_horizontal_depth_aim(v);
println!("[{}]", &arg);
println!("\tPart 1 {} x {} = {}", r1.0, r1.1, r1.0 * r1.1);
println!("\tPart 2 {} x {} = {}", r2.0, r2.1, r2.0 * r2.1);
}
}