summaryrefslogtreecommitdiff
path: root/2023/src/bin/day_21.rs
blob: e3e5df46805144fc127432b125a49d81677f70d0 (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
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
use nom::{
    branch::alt,
    character::complete::{char, line_ending},
    combinator::{map, value},
    multi::{many1, separated_list1},
    IResult,
};
use std::{collections::BTreeSet, fs, mem};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let input = fs::read_to_string("inputs/day_21.txt")?;
    let garden = WalledGarden::parser(&input).unwrap().1;

    dbg!(garden.count_closed_walls_walkable_after_steps(garden.center(), 64));
    dbg!(garden.count_open_walls_walkable_after_steps(26501365));

    // let mut open_garden = OpenGarden::parser(&input).unwrap().1;
    // let open_iters = 26501365;
    // for i in 0..open_iters {
    //     open_garden.next_mut();
    // }
    // dbg!(&open_garden.count_walkable());

    Ok(())
}

#[derive(Debug, Clone)]
struct WalledGarden {
    rocks: Vec<Vec<bool>>,
    walkable_to: Vec<Vec<bool>>,
    walkable_to_back: Vec<Vec<bool>>,
    odd_max_countable: usize,
    even_max_countable: usize,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum WalledGardenState {
    Empty,
    Walkable,
    Rock,
}

impl WalledGarden {
    fn new(tiles: Vec<Vec<WalledGardenState>>) -> WalledGarden {
        let mut odd_max_countable = 0;
        let mut even_max_countable = 0;
        let rocks: Vec<Vec<bool>> = tiles
            .iter()
            .map(|row| {
                row.iter()
                    .map(|t| *t == WalledGardenState::Rock)
                    .collect::<Vec<bool>>()
            })
            .collect();
        let walkable_to: Vec<Vec<bool>> = vec![vec![false; rocks[0].len()]; rocks.len()];

        let mut inner_figuring_out_max = WalledGarden {
            rocks: rocks.clone(),
            walkable_to_back: walkable_to.clone(),
            walkable_to: walkable_to.clone(),
            odd_max_countable: 0,
            even_max_countable: 0,
        };

        let mut unchanged_count = 0;
        for i in 1.. {
            inner_figuring_out_max.closed_walls_next_mut();

            if i % 2 == 0 {
                let new_even_max_countable = inner_figuring_out_max.count_walkable();
                if even_max_countable == new_even_max_countable {
                    unchanged_count += 1;
                } else {
                    even_max_countable = new_even_max_countable;
                }
            } else {
                let new_odd_max_countable = inner_figuring_out_max.count_walkable();
                if odd_max_countable == new_odd_max_countable {
                    unchanged_count += 1;
                } else {
                    odd_max_countable = new_odd_max_countable;
                }
            }

            if unchanged_count > 1 {
                break;
            }
        }

        WalledGarden {
            rocks,
            walkable_to_back: walkable_to.clone(),
            walkable_to: walkable_to.clone(),
            odd_max_countable,
            even_max_countable,
        }
    }

    fn parser(input: &str) -> IResult<&str, Self> {
        map(
            separated_list1(line_ending, many1(WalledGardenState::parser)),
            WalledGarden::new,
        )(input)
    }

    fn count_closed_walls_walkable_after_steps(
        &self,
        start: (usize, usize),
        steps: usize,
    ) -> usize {
        let mut garden = self.clone();
        garden.walkable_to[start.1][start.0] = true;
        for _ in 0..steps {
            garden.closed_walls_next_mut();
        }
        garden.count_walkable()
    }

    fn closed_walls_next_mut(&mut self) {
        for (y, row) in self.walkable_to_back.iter_mut().enumerate() {
            for (x, tile) in row.iter_mut().enumerate() {
                if !self.rocks[y][x] {
                    *tile = (y > 0 && self.walkable_to[y - 1][x])
                        || (y < self.walkable_to.len() - 1 && self.walkable_to[y + 1][x])
                        || (x > 0 && self.walkable_to[y][x - 1])
                        || (x < self.walkable_to[y].len() - 1 && self.walkable_to[y][x + 1]);
                }
            }
        }

        std::mem::swap(&mut self.walkable_to, &mut self.walkable_to_back);
    }

    fn count_walkable(&self) -> usize {
        self.walkable_to
            .iter()
            .flat_map(|row| row.iter())
            .filter(|s| **s)
            .count()
    }

    fn walkable_spots_when_full(&self, is_even: bool) -> usize {
        if is_even {
            self.even_max_countable
        } else {
            self.odd_max_countable
        }
    }

    fn count_open_walls_walkable_after_steps(&self, steps: usize) -> usize {
        let (size_x, size_y) = self.size();
        let (center_x, center_y) = self.center();

        let max_y_deviance = ((steps - center_y) / size_y) as isize;

        let mut total_walkable = 0;

        // The paths straight up / down, and left / right from the middle and
        // edges are clear, so it's possible to find the shortest path into
        // another chunk trivially, and looking at only that chunk is
        // equivalent.
        for chunk_y in -max_y_deviance..=max_y_deviance {
            dbg!(chunk_y);
            let y_distance = if chunk_y == 0 {
                0
            } else {
                center_y + 1 + (chunk_y.abs() as usize - 1) * size_y
            };
            let max_x_deviance = ((steps - y_distance - center_x) / size_x) as isize;
            for chunk_x in -max_x_deviance..=max_x_deviance {
                dbg!(chunk_x);
                let x_distance = if chunk_x == 0 {
                    0
                } else {
                    center_x + 1 + (chunk_x.abs() as usize - 1) * size_x
                };

                let steps_in_chunk = steps - y_distance - x_distance;

                // TODO: Identify fully walkable gardens to use the walkable_spots_when_full. Maybe for full rows at a time?
                //
                // if steps_in_chunk > 100 {
                //     total_walkable += self.walkable_spots_when_full(steps_in_chunk % 2 == 0);
                // }

                let starting_x = match chunk_x.cmp(&0) {
                    std::cmp::Ordering::Less => size_x - 1,
                    std::cmp::Ordering::Equal => center_x,
                    std::cmp::Ordering::Greater => 0,
                };
                let starting_y = match chunk_y.cmp(&0) {
                    std::cmp::Ordering::Less => size_y - 1,
                    std::cmp::Ordering::Equal => center_y,
                    std::cmp::Ordering::Greater => 0,
                };
                let starting_point = (starting_x, starting_y);
                total_walkable +=
                    self.count_closed_walls_walkable_after_steps(starting_point, steps_in_chunk);
            }
        }

        total_walkable
    }

    fn size(&self) -> (usize, usize) {
        (self.rocks[0].len(), self.rocks.len())
    }

    fn center(&self) -> (usize, usize) {
        let (size_x, size_y) = self.size();
        (size_x / 2, size_y / 2)
    }
}

impl WalledGardenState {
    fn parser(input: &str) -> IResult<&str, Self> {
        alt((
            value(WalledGardenState::Empty, char('.')),
            value(WalledGardenState::Walkable, char('S')),
            value(WalledGardenState::Rock, char('#')),
        ))(input)
    }
}

#[derive(Debug)]
struct OpenGarden {
    rockmap_size: (isize, isize),
    rocks: BTreeSet<(isize, isize)>,
    walkable: BTreeSet<(isize, isize)>,
}

impl OpenGarden {
    fn parser(input: &str) -> IResult<&str, Self> {
        map(
            separated_list1(line_ending, many1(WalledGardenState::parser)),
            |walled_garden_map| OpenGarden {
                rockmap_size: (
                    walled_garden_map.len() as isize,
                    walled_garden_map[0].len() as isize,
                ),
                rocks: walled_garden_map
                    .iter()
                    .enumerate()
                    .flat_map(|(y, row)| {
                        row.iter().enumerate().filter_map(move |(x, s)| {
                            (*s == WalledGardenState::Rock).then(|| (y as isize, x as isize))
                        })
                    })
                    .collect(),
                walkable: walled_garden_map
                    .iter()
                    .enumerate()
                    .flat_map(|(y, row)| {
                        row.iter().enumerate().filter_map(move |(x, s)| {
                            (*s == WalledGardenState::Walkable).then(|| (y as isize, x as isize))
                        })
                    })
                    .collect(),
            },
        )(input)
    }

    fn next_mut(&mut self) {
        let walkable = mem::take(&mut self.walkable);
        self.walkable = walkable
            .iter()
            .flat_map(|(y, x)| [(y - 1, *x), (y + 1, *x), (*y, x - 1), (*y, x + 1)])
            .filter(|(y, x)| !self.is_rock(*y, *x))
            .collect();
    }

    fn is_rock(&self, y: isize, x: isize) -> bool {
        let y = y.rem_euclid(self.rockmap_size.0);
        let x = x.rem_euclid(self.rockmap_size.1);
        self.rocks.contains(&(y, x))
    }

    fn count_walkable(&self) -> usize {
        self.walkable.len()
    }
}