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::>(); if p.len() == 2 && p[1].parse::().is_ok() { r.push((p[0].to_owned(), p[1].parse::().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 = 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); } }