aoc

ref: 272d6bd60122c8e81369c4b0c0b141502b77ebb5

2021/day-02/src/main.rs


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use lazy_static::lazy_static;
use regex::Regex;
use std::io;
use std::io::prelude::*;
use std::str::FromStr;

#[derive(Debug, Clone)]
enum Instruction {
    Forward(i32),
    Down(i32),
    Up(i32),
}

#[derive(Debug, Clone)]
struct InstructionParseError;

impl FromStr for Instruction {
    type Err = InstructionParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        lazy_static! {
            static ref RE: Regex = Regex::new(r"^(?P<direction>\w+) (?P<value>\d+)$").unwrap();
        }

        match RE.captures(s) {
            Some(caps) => {
                let direction = caps.name("direction").unwrap().as_str();
                let value: i32 = caps.name("value").unwrap().as_str().parse().unwrap();

                match direction {
                    "forward" => Ok(Instruction::Forward(value)),
                    "down" => Ok(Instruction::Down(value)),
                    "up" => Ok(Instruction::Up(value)),
                    _ => Err(InstructionParseError),
                }
            }

            None => Err(InstructionParseError),
        }
    }
}

#[derive(Debug, Clone)]
struct Position {
    horizontal: i32,
    depth: i32,
    aim: i32,
}

fn main() -> io::Result<()> {
    let stdin = io::stdin();
    let lines = stdin.lock().lines();

    let instructions = lines.map(|x| x.unwrap().parse().unwrap());

    let res = instructions.fold(
        Position {
            horizontal: 0,
            depth: 0,
            aim: 0,
        },
        |acc, i| match i {
            Instruction::Forward(v) => Position {
                horizontal: acc.horizontal + v,
                depth: acc.depth + (acc.aim * v),
                aim: acc.aim,
            },
            Instruction::Down(v) => Position {
                horizontal: acc.horizontal,
                depth: acc.depth,
                aim: acc.aim + v,
            },
            Instruction::Up(v) => Position {
                horizontal: acc.horizontal,
                depth: acc.depth,
                aim: acc.aim - v,
            },
        },
    );

    println!("{:?} {:?}", res, res.horizontal * res.depth);

    Ok(())
}