-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday_20.rs
356 lines (305 loc) · 9.29 KB
/
day_20.rs
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
///
/// # day_20.rs
/// Code for the day 20 of the Advent of Code challenge year 2024
///
// Imports ============================================================================== Imports
use aoc_2024::Point;
use rayon::prelude::*;
use std::{
cmp::Ordering,
collections::{BinaryHeap, HashMap},
str::FromStr,
};
// Variables =========================================================================== Variables
const INPUT: &str = include_str!("../../data/inputs/day_20.txt");
type MyPoint = Point<usize>;
#[derive(Debug, Clone)]
struct Maze {
grid: Vec<Vec<char>>,
start: MyPoint,
end: MyPoint,
}
impl Maze {
///
/// # `get`
/// Get the character at a given point in the maze.
///
/// ## Arguments
/// * `p` - The point to get the character from
///
/// ## Returns
/// * `char` - The character at the given point
fn get(&self, p: MyPoint) -> char {
let x = p.x as usize;
let y = p.y as usize;
self.grid
.get(y)
.and_then(|row| row.get(x))
.copied()
.unwrap_or('#')
}
///
/// # `is_walkable`
/// Check if a given point is walkable in the maze.
///
/// ## Arguments
/// * `point` - The point to check
///
/// ## Returns
/// * `bool` - Whether the point is walkable
fn is_walkable(&self, point: MyPoint) -> bool {
self.get(point) != '#'
}
///
/// # `neighbors`
/// Get the walkable neighbors of a given point.
///
/// ## Arguments
/// * `p` - The point to get the neighbors from
///
/// ## Returns
/// * `Vec<MyPoint>` - The walkable neighbors of the given point
fn neighbors(&self, p: MyPoint) -> Vec<MyPoint> {
[
MyPoint::new(p.x + 1, p.y),
MyPoint::new(p.x - 1, p.y),
MyPoint::new(p.x, p.y + 1),
MyPoint::new(p.x, p.y - 1),
]
.into_iter()
.filter(|&p| self.is_walkable(p))
.collect()
}
}
impl FromStr for Maze {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut grid = Vec::new();
let mut start = MyPoint::new(0, 0);
let mut end = MyPoint::new(0, 0);
for (y, line) in s.lines().enumerate() {
let mut row = Vec::new();
for (x, c) in line.chars().enumerate() {
match c {
'#' | '.' => row.push(c),
'S' => {
row.push('.');
start = MyPoint::new(x, y);
}
'E' => {
row.push('.');
end = MyPoint::new(x, y);
}
_ => return Err(()),
}
}
grid.push(row);
}
Ok(Maze { grid, start, end })
}
}
#[derive(Copy, Clone, Eq, PartialEq)]
struct PathState {
cost: usize,
position: MyPoint,
}
impl PathState {
fn new(cost: usize, position: MyPoint) -> Self {
Self { cost, position }
}
}
impl Ord for PathState {
fn cmp(&self, other: &Self) -> Ordering {
other
.cost
.cmp(&self.cost)
.then_with(|| self.position.x.cmp(&other.position.x))
.then_with(|| self.position.y.cmp(&other.position.y))
}
}
impl PartialOrd for PathState {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
struct AStar<'a> {
maze: &'a Maze,
frontier: BinaryHeap<PathState>,
came_from: HashMap<MyPoint, Option<MyPoint>>,
cost_so_far: HashMap<MyPoint, usize>,
}
impl<'a> AStar<'a> {
fn new(maze: &'a Maze) -> Self {
let mut frontier = BinaryHeap::new();
frontier.push(PathState::new(0, maze.start));
let mut came_from = HashMap::new();
let mut cost_so_far = HashMap::new();
came_from.insert(maze.start, None);
cost_so_far.insert(maze.start, 0);
Self {
maze,
frontier,
came_from,
cost_so_far,
}
}
///
/// # `find_path`
/// Find the shortest path from the start to the end of the maze.
///
/// ## Algorithm
/// A* algorithm to find the shortest path from the start to the end of the maze.
///
/// ## Returns
/// * `Option<(usize, Vec<MyPoint>)>` - The cost of the path and the path itself
fn find_path(&mut self) -> Option<(usize, Vec<MyPoint>)> {
while let Some(current) = self.frontier.pop() {
if current.position == self.maze.end {
break;
}
for next in self.maze.neighbors(current.position) {
let new_cost = self.cost_so_far[¤t.position] + 1;
if !self.cost_so_far.contains_key(&next) || new_cost < self.cost_so_far[&next] {
self.cost_so_far.insert(next, new_cost);
let priority = new_cost + next.manhattan_distance(&self.maze.end);
self.frontier.push(PathState::new(priority, next));
self.came_from.insert(next, Some(current.position));
}
}
}
self.reconstruct_path()
}
///
/// # `reconstruct_path`
/// Reconstruct the path from the start to the end of the maze.
///
/// ## Returns
/// * `Option<(usize, Vec<MyPoint>)>` - The cost of the path and the path itself
fn reconstruct_path(&self) -> Option<(usize, Vec<MyPoint>)> {
let mut path = vec![self.maze.end];
let mut current = self.maze.end;
while current != self.maze.start {
if let Some(Some(prev)) = self.came_from.get(¤t) {
current = *prev;
path.push(current);
} else {
return None;
}
}
path.reverse();
Some((self.cost_so_far[&self.maze.end], path))
}
}
struct PathFinder {
path: Vec<MyPoint>,
}
impl PathFinder {
fn new(path: Vec<MyPoint>) -> Self {
Self { path }
}
///
/// # `find_cheats`
/// Find the number of possible cheats in the path.
///
/// ## Arguments
/// * `max_cheat_time` - The maximum time to cheat
fn find_cheats(&self, max_cheat_time: usize, min_savings: usize) -> usize {
(0..self.path.len())
.par_bridge() // Parallelize the loop
.map(|start_time| self.find_cheats_from(max_cheat_time, min_savings, start_time))
.sum()
}
///
/// # `find_cheats_from`
/// Find the number of possible cheats in the path from a given start time.
///
/// ## Arguments
/// * `max_cheat_time` - The maximum time to cheat
/// * `min_savings` - The minimum time to save
/// * `start_time` - The start time to find cheats from
///
/// ## Returns
/// * `usize` - The number of possible cheats
fn find_cheats_from(
&self,
max_cheat_time: usize,
min_savings: usize,
start_time: usize,
) -> usize {
let mut viable = 0;
let cheat_start = self.path[start_time];
if start_time > self.path.len() - min_savings {
return 0;
}
let mut normal_end_time = start_time + min_savings;
while normal_end_time < self.path.len() {
let cheat_end = self.path[normal_end_time];
let cheat_dist = cheat_start.manhattan_distance(&cheat_end);
if cheat_dist > max_cheat_time {
normal_end_time += cheat_dist - max_cheat_time;
} else {
let cheat_end_time = start_time + cheat_dist;
let savings = normal_end_time - cheat_end_time;
if savings >= min_savings {
viable += 1;
}
normal_end_time += 1;
}
}
viable
}
}
pub fn response_part_1() {
println!("Day 19 - Part 1");
let start = std::time::Instant::now();
let maze = Maze::from_str(INPUT).unwrap();
let (_, normal_path) = AStar::new(&maze).find_path().unwrap();
let path_finder = PathFinder::new(normal_path);
let cheats = path_finder.find_cheats(2, 100);
let duration = start.elapsed();
println!("cheats: {cheats}");
println!("Duration: {duration:?}");
}
pub fn response_part_2() {
println!("Day 19 - Part 2");
let start = std::time::Instant::now();
let maze = Maze::from_str(INPUT).unwrap();
let (_, normal_path) = AStar::new(&maze).find_path().unwrap();
let path_finder = PathFinder::new(normal_path);
let cheats = path_finder.find_cheats(20, 100);
let duration = start.elapsed();
println!("cheats: {cheats}");
println!("Duration: {duration:?}");
}
fn main() {
response_part_1();
response_part_2();
}
#[cfg(test)]
mod tests {
use super::*;
const EXAMPLE_INPUT: &str = "\
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############";
#[test]
fn test_from_str() {
let maze = Maze::from_str(EXAMPLE_INPUT).unwrap();
assert_eq!(maze.grid.len(), 15);
assert_eq!(maze.grid[0].len(), 15);
assert_eq!(maze.start, MyPoint::new(1, 3));
assert_eq!(maze.end, MyPoint::new(5, 7));
}
}