generated from fspoettel/advent-of-code-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
16.rs
371 lines (320 loc) · 9.83 KB
/
16.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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
use std::collections::{BTreeSet, HashMap, HashSet};
use advent_of_code::{cmp_uvec2, parse_ascii_map_ivec, Dir};
use glam::UVec2;
advent_of_code::solution!();
struct Input {
start_position: UVec2,
end_position: UVec2,
walls: HashSet<UVec2>,
}
fn parse(input: &str) -> Input {
let mut start_position = None;
let mut end_position = None;
let mut walls = HashSet::new();
parse_ascii_map_ivec(input).for_each(|(pos, c)| {
let pos = pos.try_into().unwrap();
match c {
b'#' => {
walls.insert(pos);
}
b'S' => {
debug_assert!(start_position.is_none());
start_position = Some(pos);
}
b'E' => {
debug_assert!(end_position.is_none());
end_position = Some(pos);
}
b'.' => { /* nothing */ }
_ => unreachable!(),
}
});
Input {
start_position: start_position.unwrap(),
end_position: end_position.unwrap(),
walls,
}
}
pub fn part_one(input: &str) -> Option<u32> {
let Input {
start_position,
end_position,
walls,
} = parse(input);
let mut explorer = Explorer::new();
explorer.new_state(
Pos {
position: start_position,
facing: Dir::East,
},
0,
);
while let Some(state) = explorer.states.pop_first() {
// move forward
{
let new_pos = state.pos.move_forward();
let new_score = state.score + 1;
if new_pos.position == end_position {
explorer.min_score = explorer.min_score.min(new_score);
// We reach the end other moves are useless
continue;
} else if !walls.contains(&new_pos.position) {
explorer.new_state(new_pos, new_score);
}
}
// rotate clockwise
{
let new_pos = state.pos.rotate_clockwise();
let new_score = state.score + 1000;
explorer.new_state(new_pos, new_score);
}
// rotate counterclockwise
{
let new_pos = state.pos.rotate_counterclockwise();
let new_score = state.score + 1000;
explorer.new_state(new_pos, new_score);
}
}
return Some(explorer.min_score);
struct Explorer {
visited: HashMap<Pos, u32>,
states: BTreeSet<State>,
min_score: u32,
}
impl Explorer {
fn new() -> Self {
Self {
visited: HashMap::new(),
states: BTreeSet::new(),
min_score: u32::MAX,
}
}
fn new_state(&mut self, pos: Pos, score: u32) {
let should_add_new_state = if self.min_score <= score {
false
} else if let Some(&visited_score) = self.visited.get(&pos) {
score < visited_score
} else {
true
};
if should_add_new_state {
self.states.insert(State { pos, score });
self.visited.insert(pos, score);
}
}
}
#[derive(Clone, Copy, Hash, PartialEq, Eq)]
struct Pos {
position: UVec2,
facing: Dir,
}
impl Pos {
fn move_forward(self) -> Self {
let new_pos = self
.position
.wrapping_add_signed(self.facing.as_vec_down_right());
Self {
position: new_pos,
facing: self.facing,
}
}
fn rotate_clockwise(self) -> Self {
Self {
position: self.position,
facing: self.facing.rotated_clockwise(),
}
}
fn rotate_counterclockwise(self) -> Self {
Self {
position: self.position,
facing: self.facing.rotated_anti_clockwise(),
}
}
}
#[derive(PartialEq, Eq)]
struct State {
score: u32,
pos: Pos,
}
impl PartialOrd for State {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for State {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.score
.cmp(&other.score)
.then(cmp_uvec2(&self.pos.position, &other.pos.position))
.then(self.pos.facing.cmp(&other.pos.facing))
}
}
}
pub fn part_two(input: &str) -> Option<u32> {
let Input {
start_position,
end_position,
walls,
} = parse(input);
let mut explorer = Explorer::new();
explorer.new_state(
Pos {
position: start_position,
facing: Dir::East,
},
0,
HashSet::new(),
);
// The best score (lowest) is at the end of `explorer.states`
while let Some(state) = explorer.states.pop() {
// move forward
{
let new_pos = state.pos.move_forward();
let new_score = state.score + 1;
if new_pos.position == end_position {
match new_score.cmp(&explorer.min_score) {
std::cmp::Ordering::Less => {
explorer.part_of_min_path.clear();
explorer.part_of_min_path.extend(state.visited);
explorer.min_score = new_score;
}
std::cmp::Ordering::Equal => {
explorer.part_of_min_path.extend(state.visited);
}
std::cmp::Ordering::Greater => {
// nothing: the current path has a score bigger than the current min
}
}
// We reach the end other moves are useless
continue;
} else if !walls.contains(&new_pos.position) {
explorer.new_state(new_pos, new_score, state.visited.clone());
}
}
// rotate clockwise
{
let new_pos = state.pos.rotate_clockwise();
let new_score = state.score + 1000;
explorer.new_state(new_pos, new_score, state.visited.clone());
}
// rotate counterclockwise
{
let new_pos = state.pos.rotate_counterclockwise();
let new_score = state.score + 1000;
explorer.new_state(new_pos, new_score, state.visited);
}
}
let part_of_min_path_count: u32 = explorer.part_of_min_path.len().try_into().unwrap();
// we add one for the end tile
return Some(part_of_min_path_count + 1);
struct Explorer {
visited: HashMap<Pos, u32>,
/// States to explore order by score.
/// The last item has the lowest score.
states: Vec<State>,
min_score: u32,
part_of_min_path: HashSet<UVec2>,
}
impl Explorer {
fn new() -> Self {
Self {
visited: HashMap::new(),
states: Vec::new(),
min_score: u32::MAX,
part_of_min_path: HashSet::new(),
}
}
fn new_state(&mut self, pos: Pos, score: u32, mut old_visited: HashSet<UVec2>) {
let should_add_new_state = if self.min_score < score {
false
} else if let Some(&visited_score) = self.visited.get(&pos) {
score <= visited_score
} else {
true
};
if should_add_new_state {
old_visited.insert(pos.position);
self.visited.insert(pos, score);
let insert_at = match self
.states
.binary_search_by(|item| item.score.cmp(&score).reverse())
{
Ok(index) | Err(index) => index,
};
self.states.insert(
insert_at,
State {
score,
pos,
visited: old_visited,
},
);
}
}
}
#[derive(Clone, Copy, Hash, PartialEq, Eq)]
struct Pos {
position: UVec2,
facing: Dir,
}
impl Pos {
fn move_forward(self) -> Self {
let new_pos = self
.position
.wrapping_add_signed(self.facing.as_vec_down_right());
Self {
position: new_pos,
facing: self.facing,
}
}
fn rotate_clockwise(self) -> Self {
Self {
position: self.position,
facing: self.facing.rotated_clockwise(),
}
}
fn rotate_counterclockwise(self) -> Self {
Self {
position: self.position,
facing: self.facing.rotated_anti_clockwise(),
}
}
}
struct State {
score: u32,
pos: Pos,
visited: HashSet<UVec2>,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part_one_first() {
let result = part_one(&advent_of_code::template::read_file_part(
"examples", DAY, 1,
));
assert_eq!(result, Some(7036));
}
#[test]
fn test_part_one_second() {
let result = part_one(&advent_of_code::template::read_file_part(
"examples", DAY, 2,
));
assert_eq!(result, Some(11048));
}
#[test]
fn test_part_two_first() {
let result = part_two(&advent_of_code::template::read_file_part(
"examples", DAY, 1,
));
assert_eq!(result, Some(45));
}
#[test]
fn test_part_two_second() {
let result = part_two(&advent_of_code::template::read_file_part(
"examples", DAY, 2,
));
assert_eq!(result, Some(64));
}
}