use std::fs; use std::path::Path; enum Cmd { Forward(i32), Depth(i32) } impl From<&str> for Cmd { fn from(s: &str) -> Self { let (cmd, amount) = s.split_once(' ').expect("Malformed input"); let amount = amount.parse().expect("Malformed input"); match cmd { "down" => Cmd::Depth(amount), "up" => Cmd::Depth(-amount), "forward" => Cmd::Forward(amount), _ => unreachable!("Malformed input") } } } fn ex1(route: &[Cmd]) { let pos = route.iter().fold((0,0), |(f,d),c| match c { Cmd::Depth(a) => (f,d+a), Cmd::Forward(a) => (f+a,d), } ); println!("Ex1: The result is {}", pos.0 * pos.1); } fn ex2(route: &[Cmd]) { let pos = route.iter().fold((0,0,0), |(a,f,d),c| match c { Cmd::Depth(i) => (a+i,f,d), Cmd::Forward(i) => (a,f+i,d+a*i), } ); println!("Ex2: The result is {}", pos.1 * pos.2); } /* AOC21 Day 2: https://adventofcode.com/2021/day/2 */ fn main() { let input = Path::new("resources").join("input.txt"); let content = fs::read_to_string(input).expect("Unable to read input file"); let route: Vec = content.lines().map( |l| Cmd::from(l)).collect(); ex1(&route); ex2(&route); }