From 560e0401b0d2f0ced83e422df37980ddfe2fef4b Mon Sep 17 00:00:00 2001 From: Federico Igne Date: Thu, 2 Dec 2021 15:11:40 +0000 Subject: Day 2 --- day2/src/main.rs | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 day2/src/main.rs (limited to 'day2/src/main.rs') diff --git a/day2/src/main.rs b/day2/src/main.rs new file mode 100644 index 0000000..3748138 --- /dev/null +++ b/day2/src/main.rs @@ -0,0 +1,50 @@ +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); +} + -- cgit v1.2.3