AoC2021/src/day02.rs

88 lines
2.1 KiB
Rust
Raw Permalink Normal View History

2021-12-02 08:50:56 +01:00
use crate::Day;
2021-12-07 19:40:41 +01:00
use anyhow::Result;
2021-12-02 08:50:56 +01:00
pub struct Day02(Vec<Instruction>);
enum Instruction {
Forward(i32),
Down(i32),
Up(i32),
}
impl Day for Day02 {
2021-12-07 19:40:41 +01:00
fn init(content: String) -> Result<Self> {
let lines = content.lines().map(str_to_instr).collect::<Result<Vec<Instruction>>>()?;
Ok(Self(lines))
2021-12-02 08:50:56 +01:00
}
2021-12-07 19:40:41 +01:00
fn part1(&self) -> Result<String> {
2021-12-02 08:50:56 +01:00
let mut depth = 0;
let mut fw = 0;
for i in &self.0 {
match i {
Instruction::Forward(n) => fw += n,
Instruction::Down(n) => depth += n,
Instruction::Up(n) => depth -= n,
}
}
2021-12-07 19:40:41 +01:00
Ok(format!("{}", depth * fw))
2021-12-02 08:50:56 +01:00
}
2021-12-07 19:40:41 +01:00
fn part2(&self) -> Result<String> {
2021-12-02 08:50:56 +01:00
let mut depth = 0;
let mut fw = 0;
let mut aim = 0;
for i in &self.0 {
match i {
Instruction::Forward(n) => {
fw += n;
depth += aim * n;
}
2021-12-02 08:53:07 +01:00
Instruction::Down(n) => aim += n,
Instruction::Up(n) => aim -= n,
2021-12-02 08:50:56 +01:00
}
}
2021-12-07 19:40:41 +01:00
Ok(format!("{}", depth * fw))
2021-12-02 08:50:56 +01:00
}
}
2021-12-07 19:40:41 +01:00
fn str_to_instr(s: &str) -> Result<Instruction> {
2021-12-02 08:50:56 +01:00
let v = s.split(' ').collect::<Vec<&str>>();
let name = v[0];
2021-12-07 19:40:41 +01:00
let height = v[1].parse()?;
2021-12-02 08:50:56 +01:00
match name {
2021-12-07 19:40:41 +01:00
"forward" => Ok(Instruction::Forward(height)),
"up" => Ok(Instruction::Up(height)),
"down" => Ok(Instruction::Down(height)),
_ => Err(anyhow::Error::msg("This is not a valid direction!"))
2021-12-02 08:50:56 +01:00
}
}
#[cfg(test)]
mod tests {
use crate::day02::Day02;
use crate::day::Day;
2021-12-16 20:23:05 +01:00
use crate::day_tests;
2021-12-07 19:40:41 +01:00
use super::Result;
2021-12-02 08:50:56 +01:00
const D: &str = r"forward 5
down 5
forward 8
up 3
down 8
forward 2";
#[test]
2021-12-07 19:40:41 +01:00
fn part1_test() -> Result<()> {
let d2 = Day02::init(String::from(D))?;
Ok(assert_eq!("150", d2.part1()?))
2021-12-02 08:50:56 +01:00
}
#[test]
2021-12-07 19:40:41 +01:00
fn part2_test() -> Result<()> {
let d2 = Day02::init(String::from(D))?;
Ok(assert_eq!("900", d2.part2()?))
2021-12-02 08:50:56 +01:00
}
2021-12-16 20:23:05 +01:00
day_tests!(Day02, "02", "1524750", "1592426537");
2021-12-02 08:50:56 +01:00
}