summaryrefslogtreecommitdiff
path: root/aoc22/day8/src/main.rs
blob: 66b23228d5b135676a529e1a40e3241c57cbb24a (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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
fn main() {
    let input = lib::read_input(8);

    part1(&input);
    part2(&input);
}

fn part1(input: &str) {
    let input = input.split_whitespace().map(|x| x.bytes().collect::<Vec<_>>()).collect::<Vec<_>>();

    let mut ans = 0;
    for (y, line) in input.iter().enumerate() {
        for (x, _) in line.iter().enumerate() {
            if visible(&input, x, y) {
                ans += 1;
            }
        }
    }
    println!("{}", ans);
}

fn part2(input: &str) {
    let input = input.split_whitespace().map(|x| x.bytes().collect::<Vec<_>>()).collect::<Vec<_>>();

    let mut ans = 0;
    for (y, line) in input.iter().enumerate() {
        for (x, _) in line.iter().enumerate() {
            ans = ans.max(scenic_score(&input, x, y));
        }
    }
    println!("{}", ans);
}

fn scenic_score(heights: &[Vec<u8>], x: usize, y: usize) -> u32 {
    let mut score = 1;
    for (dy, dx) in &[(0, 1), (0, -1), (1, 0), (-1, 0)] {
        let height = heights[y][x];

        let mut seen = 0;

        let mut sx = x as i32;
        let mut sy = y as i32;
        loop {
            sx += dx;
            sy += dy;

            if sx < 0 || sy < 0 || sy >= heights.len() as i32 || sx >= heights[sy as usize].len() as i32 {
                break;
            }

            seen += 1;

            if heights[sy as usize][sx as usize] >= height {
                break;
            }
        }
        score *= seen;
    }
    score
}

fn visible(heights: &[Vec<u8>], x: usize, y: usize) -> bool {
    for (dy, dx) in &[(0, 1), (0, -1), (1, 0), (-1, 0)] {
        let height = heights[y][x];

        let mut sx = x as i32;
        let mut sy = y as i32;

        loop {
            sx += dx;
            sy += dy;

            if sx < 0 || sy < 0 || sx >= heights[0].len() as i32 || sy >= heights.len() as i32 {
                return true;
            }

            if heights[sy as usize][sx as usize] >= height {
                break;
            }
        }
    }
    return false;
}