From baf4910870a6e8999802b9a4a22eabd4142a34e3 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 1 Dec 2022 22:30:22 +0100 Subject: Move all Advent of Codes into one repo --- 2021/src/day02.rs | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 2021/src/day02.rs (limited to '2021/src/day02.rs') diff --git a/2021/src/day02.rs b/2021/src/day02.rs new file mode 100644 index 0000000..e64d2e9 --- /dev/null +++ b/2021/src/day02.rs @@ -0,0 +1,67 @@ +use std::str::FromStr; +use std::error::Error; +use std::fs; +use std::path::Path; + +#[derive(PartialEq, Debug)] +enum Command { + Forward(i32), + Down(i32), + Up(i32) +} + +#[derive(Debug)] +struct ParseCommandError; + +impl FromStr for Command { + type Err = ParseCommandError; + + fn from_str(s: &str) -> Result { + let i = s.find(' ').ok_or(ParseCommandError)?; + let num = s[i + 1..].parse::().map_err(|_| ParseCommandError)?; + match &s[..i] { + "forward" => Ok(Command::Forward(num)), + "down" => Ok(Command::Down(num)), + "up" => Ok(Command::Up(num)), + _ => Err(ParseCommandError) + } + } +} + +#[cfg(part1)] +pub fn solve(path: &Path) -> Result<(), Box> { + let data = fs::read_to_string(path)?; + let mut hor = 0; + let mut depth = 0; + for command in data.lines().filter_map(|x| x.parse::().ok()) { + match command { + Command::Forward(v) => hor += v, + Command::Down(v) => depth += v, + Command::Up(v) => depth -= v + } + } + + println!("{}", hor * depth); + Ok(()) +} + +#[cfg(part2)] +pub fn solve(path: &Path) -> Result<(), Box> { + let data = fs::read_to_string(path)?; + let mut aim = 0; + let mut hor = 0; + let mut depth = 0; + for command in data.lines().filter_map(|x| x.parse::().ok()) { + match command { + Command::Forward(v) => { + hor += v; + depth += aim * v; + }, + Command::Down(v) => aim += v, + Command::Up(v) => aim -= v + } + } + + println!("{}", hor * depth); + Ok(()) +} -- cgit v1.2.3