Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@edg-l
Last active December 2, 2021 08:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edg-l/b8f6fcd860411de8b9ec8158f6491477 to your computer and use it in GitHub Desktop.
Save edg-l/b8f6fcd860411de8b9ec8158f6491477 to your computer and use it in GitHub Desktop.
aoc2021 day 2 b in rust
use std::{
fmt::{self, write},
str::FromStr,
};
#[derive(Debug, Clone)]
struct ParseError(String);
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write(f, format_args!("error parsing '{}'", self.0))
}
}
#[derive(Debug, Clone, Copy)]
enum Command {
Forward(i32),
Down(i32),
Up(i32),
}
impl FromStr for Command {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut data = s.splitn(2, ' ');
let command = data.next().ok_or_else(|| ParseError(s.to_string()))?;
let value = data
.next()
.ok_or_else(|| ParseError(s.to_string()))?
.parse::<i32>()
.map_err(|e| ParseError(format!("error parsing line '{}' due to {}", s, e)))?;
Ok(match command {
"forward" => Self::Forward(value),
"down" => Self::Down(value),
"up" => Self::Up(value),
_ => return Err(ParseError("command not found".to_string())),
})
}
}
struct Submarine {
horizontal: i32,
depth: i32,
aim: i32,
}
impl Default for Submarine {
fn default() -> Self {
Self {
horizontal: 0,
depth: 0,
aim: 0,
}
}
}
impl Submarine {
pub fn execute(&mut self, command: Command) {
match command {
Command::Down(x) => self.aim += x,
Command::Up(x) => self.aim -= x,
Command::Forward(x) => {
self.horizontal += x;
self.depth += self.aim * x;
}
}
}
pub fn execute_multiple(&mut self, commands: impl Iterator<Item = Command>) {
commands.for_each(|command| self.execute(command))
}
pub fn position(&self) -> i32 {
self.horizontal * self.depth
}
}
fn main() {
let input = include_str!("inputs/day_2.txt");
let lines = input.lines();
let commands = lines.map(|line| Command::from_str(line).expect("error parsing line"));
let mut submarine = Submarine::default();
submarine.execute_multiple(commands);
println!("The result is: {}", submarine.position())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment