-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday16.rs
More file actions
302 lines (267 loc) · 7.83 KB
/
day16.rs
File metadata and controls
302 lines (267 loc) · 7.83 KB
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
use std::{
collections::{BinaryHeap, HashMap, HashSet},
hash::Hash,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum Direction {
N,
E,
S,
W,
}
impl Direction {
pub fn rotate_left(&self) -> Self {
match self {
Direction::N => Direction::W,
Direction::W => Direction::S,
Direction::S => Direction::E,
Direction::E => Direction::N,
}
}
pub fn rotate_right(&self) -> Self {
match self {
Direction::N => Direction::E,
Direction::E => Direction::S,
Direction::S => Direction::W,
Direction::W => Direction::N,
}
}
pub fn mirror(&self) -> Self {
match self {
Direction::N => Direction::S,
Direction::E => Direction::W,
Direction::S => Direction::N,
Direction::W => Direction::E,
}
}
pub fn all() -> Vec<Self> {
vec![Direction::N, Direction::E, Direction::S, Direction::W]
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct Point {
row: usize,
col: usize,
}
impl Point {
pub fn step(&self, dir: Direction) -> Option<Self> {
match dir {
Direction::N => Some(Point {
row: self.row.checked_sub(1)?,
col: self.col,
}),
Direction::E => Some(Point {
row: self.row,
col: self.col + 1,
}),
Direction::S => Some(Point {
row: self.row + 1,
col: self.col,
}),
Direction::W => Some(Point {
row: self.row,
col: self.col.checked_sub(1)?,
}),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct State {
pos: Point,
dir: Direction,
cost: usize,
}
impl State {
pub fn new_states(&self) -> Vec<State> {
Vec::from([
State {
pos: self.pos.step(self.dir).unwrap(),
dir: self.dir,
cost: self.cost + 1,
},
State {
pos: self.pos,
dir: self.dir.rotate_left(),
cost: self.cost + 1000,
},
State {
pos: self.pos,
dir: self.dir.rotate_right(),
cost: self.cost + 1000,
},
])
}
}
impl Ord for State {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
other.cost.cmp(&self.cost)
}
}
impl PartialOrd for State {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Grid {
walls: HashSet<Point>,
start: Point,
end: Point,
}
impl Grid {
pub fn from_input(input: &str) -> Self {
let mut walls = HashSet::new();
let mut start = Point { row: 0, col: 0 };
let mut end = Point { row: 0, col: 0 };
for (row, line) in input.lines().enumerate() {
for (col, ch) in line.trim().chars().enumerate() {
let point = Point { row, col };
match ch {
'#' => {
walls.insert(point);
}
'S' => {
start = point;
}
'E' => {
end = point;
}
'.' => {}
_ => {
unreachable!();
}
}
}
}
Self { walls, start, end }
}
fn new_states(&self, current: &State) -> Vec<State> {
current
.new_states()
.iter()
.filter_map(|&state| match self.walls.contains(&state.pos) {
true => None,
false => Some(state),
})
.collect()
}
pub fn shortest_distances(
&self,
start_point: Point,
start_direction: Direction,
) -> HashMap<(Point, Direction), usize> {
let mut distance = HashMap::new();
let mut heap = BinaryHeap::from([State {
pos: start_point,
dir: start_direction,
cost: 0,
}]);
while let Some(current) = heap.pop() {
if distance.contains_key(&(current.pos, current.dir)) {
continue;
}
distance.insert((current.pos, current.dir), current.cost);
for child in self.new_states(¤t) {
heap.push(child);
}
}
distance
}
pub fn shortest_path(&self) -> Option<usize> {
let distances = self.shortest_distances(self.start, Direction::E);
Direction::all()
.iter()
.filter_map(|&dir| match distances.get(&(self.end, dir)) {
Some(&distance) => Some(distance),
None => None,
})
.min()
}
// Based on idea by @jenuk
pub fn points_on_shortest_path(&self) -> usize {
let forward_distances = self.shortest_distances(self.start, Direction::E);
let end_direction = Direction::all()
.iter()
.filter_map(|&dir| match forward_distances.get(&(self.end, dir)) {
Some(&distance) => Some((dir, distance)),
None => None,
})
.min_by_key(|&(_, distance)| distance)
.unwrap()
.0;
let backward_distances = self.shortest_distances(self.end, end_direction.mirror());
HashSet::<Point>::from_iter(forward_distances.iter().filter_map(
|((point, direction), &distance)| {
match backward_distances.get(&(*point, direction.mirror())) {
Some(&backward_distance) => {
if distance + backward_distance
== forward_distances[&(self.end, end_direction)]
{
Some(*point)
} else {
None
}
}
None => None,
}
},
))
.len()
}
#[allow(dead_code)]
fn print_maze(&self, visited: &HashSet<Point>) {
let (n_rows, n_cols) = self.walls.iter().fold((0, 0), |(max_row, max_col), point| {
(max_row.max(point.row + 1), max_col.max(point.col + 1))
});
for row in 0..n_rows {
for col in 0..n_cols {
let point = Point { row, col };
if self.walls.contains(&point) {
print!("#");
} else if point == self.start {
print!("S");
} else if point == self.end {
print!("E");
} else if visited.contains(&point) {
print!("O");
} else {
print!(".");
}
}
println!();
}
}
}
pub fn task01(input: &str) -> String {
let grid = Grid::from_input(input);
grid.shortest_path().unwrap().to_string()
}
pub fn task02(input: &str) -> String {
let grid = Grid::from_input(input);
grid.points_on_shortest_path().to_string()
}
#[cfg(test)]
mod tests {
use super::super::fs_utils::{read_example, read_input};
use super::*;
#[test]
fn test_task01() {
let input = read_example(16, 2);
assert_eq!(task01(&input), "11048");
}
#[test]
fn run_task01() {
let input = read_input(16);
assert_eq!(task01(&input), "91464");
}
#[test]
fn test_task02() {
let input = read_example(16, 2);
assert_eq!(task02(&input), "64");
}
#[test]
fn run_task02() {
let input = read_input(16);
assert_eq!(task02(&input), "494");
}
}