advent-of-code-2021/day2/src/main.rs
Louis Vallat f420e96477
Added day 2 code for part 1 and 2
Signed-off-by: Louis Vallat <louis@louis-vallat.xyz>
2021-12-03 21:48:01 +01:00

58 lines
1.7 KiB
Rust

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);
}
}