summaryrefslogtreecommitdiff
path: root/2021/src/day02.rs
diff options
context:
space:
mode:
authorBond_009 <bond.009@outlook.com>2022-12-01 22:30:22 +0100
committerBond_009 <bond.009@outlook.com>2022-12-01 22:30:22 +0100
commitbaf4910870a6e8999802b9a4a22eabd4142a34e3 (patch)
tree2d11443dc21e53bd0d99d015cf789937d6d95862 /2021/src/day02.rs
parent49d0c908f24b2c193c9deed1716fe36061ba26a1 (diff)
Move all Advent of Codes into one repo
Diffstat (limited to '2021/src/day02.rs')
-rw-r--r--2021/src/day02.rs67
1 files changed, 67 insertions, 0 deletions
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<Self, Self::Err> {
+ let i = s.find(' ').ok_or(ParseCommandError)?;
+ let num = s[i + 1..].parse::<i32>().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<dyn Error>> {
+ 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::<Command>().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<dyn Error>> {
+ 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::<Command>().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(())
+}