summaryrefslogtreecommitdiff
path: root/2021/day02/src/main.rs
blob: 3748138c9ffd355b765f14832322f112d73b3bd8 (plain) (blame)
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
use std::fs;
use std::path::Path;

enum Cmd {
    Forward(i32),
    Depth(i32)
}

impl From<&str> for Cmd {
    fn from(s: &str) -> Self {
        let (cmd, amount) = s.split_once(' ').expect("Malformed input");
        let amount = amount.parse().expect("Malformed input");
        match cmd {
            "down"    => Cmd::Depth(amount),
            "up"      => Cmd::Depth(-amount),
            "forward" => Cmd::Forward(amount),
            _         => unreachable!("Malformed input")
        }
    }
}

fn ex1(route: &[Cmd]) {
    let pos = route.iter().fold((0,0),
        |(f,d),c| match c {
            Cmd::Depth(a) => (f,d+a),
            Cmd::Forward(a) => (f+a,d),
        }
    );
    println!("Ex1: The result is {}", pos.0 * pos.1);
}

fn ex2(route: &[Cmd]) {
    let pos = route.iter().fold((0,0,0),
        |(a,f,d),c| match c {
            Cmd::Depth(i) => (a+i,f,d),
            Cmd::Forward(i) => (a,f+i,d+a*i),
        }
    );
    println!("Ex2: The result is {}", pos.1 * pos.2);
}

/* AOC21 Day 2: https://adventofcode.com/2021/day/2 */
fn main() {
    let input = Path::new("resources").join("input.txt");
    let content = fs::read_to_string(input).expect("Unable to read input file");
    let route: Vec<Cmd> = content.lines().map( |l| Cmd::from(l)).collect();
    ex1(&route);
    ex2(&route);
}