summaryrefslogtreecommitdiff
path: root/2024_rust/src/bin/day2.rs
blob: 05d5b75a8706b7e134935210d8943b7032d83042 (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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#[derive(PartialEq, Clone, Copy)]
enum Direction {
    Up,
    Down,
    Unknown,
}
use Direction::*;

fn is_safe(levels: &[u32]) -> bool {
    let mut direction = Unknown;
    for i in 0..levels.len() - 1 {
        let [x, y] = levels[i..=i + 1] else {
            unreachable!()
        };
        let (diff, d) = if x > y { (x - y, Down) } else { (y - x, Up) };
        if direction == Unknown {
            direction = d;
        }
        if diff == 0 || diff > 3 || direction != d {
            return false;
        }
    }
    true
}

fn p1(input: &str) -> String {
    let mut total = 0;
    for report in input.lines() {
        let levels: Vec<u32> = report
            .split_whitespace()
            .map(|l| l.parse().unwrap())
            .collect();
        if is_safe(&levels) {
            total += 1;
        }
    }

    total.to_string()
}

fn is_safe_with_dampener(levels: &[u32]) -> bool {
    for i in 0..levels.len() {
        let mut levels_without_i: Vec<u32> = levels.to_vec();
        levels_without_i.remove(i);
        if is_safe(&levels_without_i) {
            return true;
        }
    }
    false
}

fn p2(input: &str) -> String {
    let mut total = 0;
    for report in input.lines() {
        let levels: Vec<u32> = report
            .split_whitespace()
            .map(|l| l.parse().unwrap())
            .collect();
        if is_safe(&levels) || is_safe_with_dampener(&levels) {
            total += 1;
        }
    }

    total.to_string()
}

fn main() {
    aoc2024::run_day("2", p1, p2);
}