DEVELOPMENT ENVIRONMENT

~liljamo/aoc2024

ref: 8f7092f19eb6708676b95c93cc9012d57d80a06b aoc2024/src/day12/part2.rs -rw-r--r-- 7.7 KiB
8f7092f1Jonni Liljamo feat: day12 a month ago
                                                                                
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
use std::{
    collections::{BTreeSet, HashSet},
    fs::File,
    io::{BufRead, BufReader},
    path::Path,
};

fn get_around(map: &[Vec<char>], p: (usize, usize)) -> Vec<(char, usize, usize)> {
    let mut around_us = vec![];
    if p.0 > 0 {
        let (y, x) = (p.0 - 1, p.1);
        around_us.push((map[y][x], y, x));
    }
    if let Some(row) = map.get(p.0 + 1) {
        let (y, x) = (p.0 + 1, p.1);
        around_us.push((row[x], y, x));
    }
    if p.1 > 0 {
        let (y, x) = (p.0, p.1 - 1);
        around_us.push((map[y][x], y, x));
    }
    if let Some(f) = map[p.0].get(p.1 + 1) {
        let (y, x) = (p.0, p.1 + 1);
        around_us.push((*f, y, x));
    }
    around_us
}

#[derive(Debug, Eq, Hash, PartialEq)]
struct Region {
    c: char,
    plots: BTreeSet<Plot>,
}

impl Region {
    fn read_from_map(map: &[Vec<char>], c: &char, p: (usize, usize)) -> Self {
        let mut region = Region {
            c: *c,
            plots: BTreeSet::new(),
        };
        region.plots.insert(Plot {
            y: p.0,
            x: p.1,
            perimiter: (get_around(map, (p.0, p.1))
                .iter()
                .filter(|(f, _, _)| f == c)
                .collect::<Vec<_>>()
                .len() as i32
                - 4)
            .unsigned_abs() as usize,
        });
        region.read_recurse(map, c, p);
        region
    }

    fn read_recurse(&mut self, map: &[Vec<char>], c: &char, p: (usize, usize)) {
        for (f, y, x) in get_around(map, p) {
            if f == *c {
                let perimiter = (get_around(map, (y, x))
                    .iter()
                    .filter(|(f, _, _)| f == c)
                    .collect::<Vec<_>>()
                    .len() as i32
                    - 4)
                .unsigned_abs() as usize;
                if self.plots.insert(Plot { y, x, perimiter }) {
                    self.read_recurse(map, c, (y, x));
                }
            }
        }
    }

    fn get_fence_cost(&self, map: &[Vec<char>], max_pos: usize) -> usize {
        // Okay so, instead of perimiters * len, sides * len
        // form all possible rows and columns of plots
        // AAAA
        // BB, B, B, BB
        //     B, B
        // C, C, CC, C
        //    C,     C
        // D
        // EEE

        let mut rows_initial: Vec<Vec<Plot>> = vec![];
        for i in 0..max_pos {
            let mut a: Vec<Plot> = self.plots.iter().filter(|p| p.y == i).cloned().collect();
            if !a.is_empty() {
                a.sort_by_key(|p| p.x);
                rows_initial.push(a);
            }
        }
        let mut rows: Vec<Vec<Plot>> = vec![];
        for row in &rows_initial {
            let mut real_rows: Vec<Vec<Plot>> = vec![];
            let mut last = None;
            let mut current_real_row: Vec<Plot> = vec![];
            for p in row {
                if last.is_none() {
                    current_real_row.push(p.clone());
                    last = Some(p);
                    continue;
                }

                if p.x != last.unwrap().x + 1 {
                    real_rows.push(current_real_row.clone());
                    current_real_row.clear();
                }
                current_real_row.push(p.clone());
                last = Some(p);
            }
            real_rows.push(current_real_row.clone());
            rows.append(&mut real_rows);
        }

        let mut row_sides = 0;
        for row in rows {
            // top
            let mut sides = 0;
            let mut side_length = 0;
            for p in &row {
                let fence = if p.y > 0 {
                    map[p.y - 1][p.x] != self.c
                } else {
                    true
                };
                if fence {
                    side_length += 1;
                } else if side_length > 0 {
                    sides += 1;
                    side_length = 0;
                }
            }
            if side_length > 0 {
                sides += 1;
            }
            row_sides += sides;

            // bottom
            let mut sides = 0;
            let mut side_length = 0;
            for p in &row {
                let fence = if let Some(below) = map.get(p.y + 1) {
                    below[p.x] != self.c
                } else {
                    true
                };
                if fence {
                    side_length += 1;
                } else if side_length > 0 {
                    sides += 1;
                    side_length = 0;
                }
            }
            if side_length > 0 {
                sides += 1;
            }
            row_sides += sides;
        }

        let mut cols_initial: Vec<Vec<Plot>> = vec![];
        for i in 0..max_pos {
            let mut a: Vec<Plot> = self.plots.iter().filter(|p| p.x == i).cloned().collect();
            if !a.is_empty() {
                a.sort_by_key(|p| p.y);
                cols_initial.push(a);
            }
        }
        let mut cols: Vec<Vec<Plot>> = vec![];
        for col in &cols_initial {
            let mut real_cols: Vec<Vec<Plot>> = vec![];
            let mut last = None;
            let mut current_real_col: Vec<Plot> = vec![];
            for p in col {
                if last.is_none() {
                    current_real_col.push(p.clone());
                    last = Some(p);
                    continue;
                }

                if p.y != last.unwrap().y + 1 {
                    real_cols.push(current_real_col.clone());
                    current_real_col.clear();
                }
                current_real_col.push(p.clone());
                last = Some(p);
            }
            real_cols.push(current_real_col.clone());
            cols.append(&mut real_cols);
        }

        let mut col_sides = 0;
        for col in cols {
            // right
            let mut sides = 0;
            let mut side_length = 0;
            for p in &col {
                let fence = if p.x > 0 {
                    map[p.y][p.x - 1] != self.c
                } else {
                    true
                };
                if fence {
                    side_length += 1;
                } else if side_length > 0 {
                    sides += 1;
                    side_length = 0;
                }
            }
            if side_length > 0 {
                sides += 1;
            }
            col_sides += sides;

            // left
            let mut sides = 0;
            let mut side_length = 0;
            for p in &col {
                let fence = if let Some(left) = map[p.y].get(p.x + 1) {
                    *left != self.c
                } else {
                    true
                };
                if fence {
                    side_length += 1;
                } else if side_length > 0 {
                    sides += 1;
                    side_length = 0;
                }
            }
            if side_length > 0 {
                sides += 1;
            }
            col_sides += sides;
        }

        self.plots.len() * (row_sides + col_sides)
    }
}

#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
struct Plot {
    y: usize,
    x: usize,
    perimiter: usize,
}

pub fn part_two(input: &Path) -> anyhow::Result<usize> {
    let reader = BufReader::new(File::open(input)?);

    let mut map: Vec<Vec<char>> = vec![];
    for line in reader.lines() {
        map.push(line?.chars().collect());
    }
    let mut regions: HashSet<Region> = HashSet::new();
    for (y, row) in map.iter().enumerate() {
        for (x, c) in row.iter().enumerate() {
            regions.insert(Region::read_from_map(&map, c, (y, x)));
        }
    }

    Ok(regions
        .iter()
        .map(|r| -> usize { r.get_fence_cost(&map, map.len()) })
        .sum())
}