summaryrefslogtreecommitdiff
path: root/2021/src/bin/day_9.rs
blob: 5ef0daec4e9bf1254f8efb33e0607c9f9d4ee748 (plain)
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
use nom::{
    character::complete::{line_ending, one_of},
    combinator::{map, map_res},
    multi::{many1, separated_list1},
    IResult,
};
use std::fs;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let input = fs::read_to_string("inputs/day_9.txt")?;
    let height_map = parse_height_map(&input).unwrap().1;
    let risk_level_sum: RiskLevel = height_map.risk_levels().into_iter().sum();
    dbg!(risk_level_sum);

    let mut basin_sizes: Vec<u32> = height_map.basins.iter().map(|basin| basin.size).collect();
    basin_sizes.sort_unstable_by(|a, b| b.cmp(a));
    dbg!(basin_sizes.iter().take(3).product::<u32>());

    Ok(())
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
struct Height(u8);
#[derive(
    Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, derive_more::Add, derive_more::Sum,
)]
struct RiskLevel(u32);

impl From<Height> for RiskLevel {
    fn from(h: Height) -> Self {
        RiskLevel(h.0 as u32 + 1)
    }
}

#[derive(Debug, Default)]
struct Basin {
    size: u32,
}

#[derive(Debug)]
struct HeightMap {
    heights: Vec<Vec<Height>>,
    low_points: Vec<(usize, usize)>,
    basins: Vec<Basin>,
    basin_map: Vec<Vec<Option<usize>>>,
}

impl HeightMap {
    fn new(heights: Vec<Vec<Height>>) -> HeightMap {
        let mut height_map = HeightMap {
            heights,
            low_points: Vec::new(),
            basins: Vec::new(),
            basin_map: Vec::new(),
        };
        height_map.init_low_points();
        height_map.init_basins();
        height_map
    }
}

impl HeightMap {
    fn init_low_points(&mut self) {
        self.low_points = Vec::new();
        for y in 0..self.heights.len() {
            for x in 0..self.heights[y].len() {
                let current = self.heights[y][x];
                let mut is_low_point = true;
                let edges = [
                    (x as isize - 1, y as isize),
                    (x as isize + 1, y as isize),
                    (x as isize, y as isize - 1),
                    (x as isize, y as isize + 1),
                ];
                for edge in edges {
                    if self
                        .get_height(edge.0, edge.1)
                        .map_or(false, |other| other <= current)
                    {
                        is_low_point = false;
                    }
                }

                if is_low_point {
                    self.low_points.push((x, y));
                }
            }
        }
    }

    fn init_basins(&mut self) {
        for low_point in self.low_points.clone() {
            if self
                .get_basin(low_point.0 as isize, low_point.1 as isize)
                .is_some()
            {
                continue;
            }

            let mut basin = Basin::default();
            let basin_index = self.basins.len();
            self.set_basin(basin_index, low_point.0, low_point.1);
            basin.size += 1;
            let mut boundary = vec![low_point];
            while boundary.len() > 0 {
                let (x, y) = boundary.pop().unwrap();
                let edges = [
                    (x as isize - 1, y as isize),
                    (x as isize + 1, y as isize),
                    (x as isize, y as isize - 1),
                    (x as isize, y as isize + 1),
                ];
                for edge in edges {
                    if self
                        .get_height(edge.0, edge.1)
                        .map_or(false, |other| other != Height(9))
                        && self.get_basin(edge.0, edge.1).is_none()
                    {
                        let x = edge.0 as usize;
                        let y = edge.1 as usize;
                        self.set_basin(basin_index, x, y);
                        basin.size += 1;
                        boundary.push((x, y));
                    }
                }
            }
            self.basins.push(basin);
        }
    }

    fn get_height(&self, x: isize, y: isize) -> Option<Height> {
        if x < 0 || y < 0 {
            None
        } else {
            let x = x as usize;
            let y = y as usize;
            self.heights.get(y).and_then(|row| row.get(x)).cloned()
        }
    }

    fn get_basin(&self, x: isize, y: isize) -> Option<usize> {
        if x < 0 || y < 0 {
            None
        } else {
            let x = x as usize;
            let y = y as usize;
            self.basin_map
                .get(y)
                .and_then(|row| row.get(x))
                .cloned()
                .flatten()
        }
    }

    fn set_basin(&mut self, basin: usize, x: usize, y: usize) {
        while self.basin_map.len() <= y {
            self.basin_map.push(Vec::new());
        }
        while self.basin_map[y].len() <= x {
            self.basin_map[y].push(None);
        }
        self.basin_map[y][x] = Some(basin);
    }

    fn risk_levels(&self) -> Vec<RiskLevel> {
        self.low_points
            .iter()
            .copied()
            .map(|(x, y)| self.heights[y][x].clone().into())
            .collect()
    }
}

fn parse_height_map(input: &str) -> IResult<&str, HeightMap> {
    map(separated_list1(line_ending, parse_row), HeightMap::new)(input)
}

fn parse_row(input: &str) -> IResult<&str, Vec<Height>> {
    many1(parse_height)(input)
}

fn parse_height(input: &str) -> IResult<&str, Height> {
    map_res(one_of("0123456789"), |digit| {
        digit.to_string().parse().map(Height)
    })(input)
}