-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.rs
282 lines (243 loc) · 7.04 KB
/
mod.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
use std::{collections::HashMap, fmt::Display};
use aoc_runner_derive::{aoc, aoc_generator};
#[allow(unused)]
use itertools::Itertools;
use crate::utils::point::Point;
type Output = isize;
type Map = HashMap<Point, Position>;
type Commands = Vec<Direction>;
type Input = (Map, Commands);
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Position {
Empty,
Wall,
Cargo,
Robot,
}
impl Display for Position {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
Position::Empty => '.',
Position::Wall => '#',
Position::Cargo => 'O',
Position::Robot => '@',
}
)
}
}
#[derive(Clone, Copy, Debug)]
pub enum Direction {
Up,
Right,
Down,
Left,
}
impl From<char> for Direction {
fn from(value: char) -> Self {
match value {
'^' => Self::Up,
'>' => Self::Right,
'v' => Self::Down,
'<' => Self::Left,
d => panic!("Unkown direction: {}", d),
}
}
}
impl From<&Direction> for Point {
fn from(value: &Direction) -> Self {
match value {
Direction::Up => Point::from((0, -1)),
Direction::Right => Point::from((1, 0)),
Direction::Down => Point::from((0, 1)),
Direction::Left => Point::from((-1, 0)),
}
}
}
impl From<char> for Position {
fn from(value: char) -> Self {
match value {
'.' => Self::Empty,
'#' => Self::Wall,
'O' => Self::Cargo,
'@' => Self::Robot,
o => panic!("Unkown space occupant: {}", o),
}
}
}
#[aoc_generator(day15, part1)]
pub fn input_generator(input: &str) -> Input {
let (map, commands) = input.split_once("\n\n").unwrap();
let map = map
.lines()
.enumerate()
.flat_map(|(y, row)| {
row.chars()
.enumerate()
.map(move |(x, c)| (Point::from((x as isize, y as isize)), Position::from(c)))
})
.collect::<HashMap<Point, Position>>();
let commands = commands
.chars()
.filter(|c| *c != '\n')
.map(Direction::from)
.collect::<Vec<Direction>>();
(map, commands)
}
pub fn shift(pos: Point, dir: &Direction, map: &mut Map) -> Option<Point> {
let new_pos = pos + Point::from(dir);
if map[&new_pos] == Position::Wall {
return None;
}
if map[&new_pos] == Position::Cargo {
if let Some(nnp) = shift(new_pos, dir, map) {
*map.get_mut(&nnp).unwrap() = Position::Cargo;
*map.get_mut(&new_pos).unwrap() = Position::Empty;
} else {
return None;
}
}
Some(new_pos)
}
pub fn compute_gps(pos: &Point) -> Output {
pos['y'] * 100 + pos['x']
}
pub fn print_map<T>(map: &HashMap<Point, T>)
where
T: Display,
{
let x_max = map.keys().map(|pos| pos['x']).max().unwrap();
let y_max = map.keys().map(|pos| pos['y']).max().unwrap();
for y in 0..=y_max {
for x in 0..=x_max {
print!("{}", map[&Point::from((x, y))]);
}
println!();
}
}
#[aoc(day15, part1)]
pub fn solve_part1(input: &Input) -> Output {
let (map, commands) = input;
let mut map = map.clone();
let mut pos = *map
.iter()
.find(|(_, occ)| **occ == Position::Robot)
.unwrap()
.0;
for command in commands {
let tmp = map.clone();
if let Some(new_pos) = shift(pos, command, &mut map) {
*map.get_mut(&new_pos).unwrap() = Position::Robot;
*map.get_mut(&pos).unwrap() = Position::Empty;
pos = new_pos;
} else {
map = tmp;
}
}
map.iter()
.filter(|(_, occ)| **occ == Position::Cargo)
.map(|(pos, _)| compute_gps(pos))
.sum()
}
type Map2 = HashMap<Point, char>;
type Input2 = (Map2, Commands);
#[aoc_generator(day15, part2)]
pub fn input_generator2(input: &str) -> Input2 {
let (map, commands) = input.split_once("\n\n").unwrap();
let map = map
.replace("#", "##")
.replace("O", "[]")
.replace(".", "..")
.replace("@", "@.");
let map = map
.lines()
.enumerate()
.flat_map(|(y, row)| {
row.chars()
.enumerate()
.map(move |(x, c)| (Point::from((x as isize, y as isize)), c))
})
.collect::<HashMap<Point, char>>();
let commands = commands
.chars()
.filter(|c| *c != '\n')
.map(Direction::from)
.collect::<Vec<Direction>>();
(map, commands)
}
pub fn shift2(pos: Point, dir: &Direction, map: &mut Map2) -> Option<Point> {
let new_pos = pos + Point::from(dir);
if map[&new_pos] == '#' {
return None;
}
if map[&new_pos] == '[' {
shift2(new_pos + Point::from(&Direction::Right), dir, map)?;
shift2(new_pos, dir, map)?;
}
if map[&new_pos] == ']' {
shift2(new_pos + Point::from(&Direction::Left), dir, map)?;
shift2(new_pos, dir, map)?;
}
(*map.get_mut(&new_pos).unwrap(), *map.get_mut(&pos).unwrap()) = (map[&pos], map[&new_pos]);
Some(new_pos)
}
#[aoc(day15, part2)]
pub fn solve_part2(input: &Input2) -> Output {
let (map, commands) = input;
let mut map = map.clone();
let mut pos = *map.iter().find(|(_, occ)| **occ == '@').unwrap().0;
for command in commands {
let tmp = map.clone();
if let Some(new_pos) = shift2(pos, command, &mut map) {
pos = new_pos;
} else {
map = tmp;
}
}
map.iter()
.filter(|(_, occ)| **occ == '[')
.map(|(pos, _)| compute_gps(pos))
.sum()
}
pub fn part1(input: &str) -> impl std::fmt::Display {
solve_part1(&input_generator(input))
}
pub fn part2(input: &str) -> impl std::fmt::Display {
solve_part2(&input_generator2(input))
}
#[cfg(test)]
mod tests {
use super::*;
fn sample() -> &'static str {
"##########
#..O..O.O#
#......O.#
#.OO..O.O#
#..O@..O.#
#O#..O...#
#O..O..O.#
#.OO.O.OO#
#....O...#
##########
<vv>^<v^>v>^vv^v>v<>v^v<v<^vv<<<^><<><>>v<vvv<>^v^>^<<<><<v<<<v^vv^v>^
vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<<v<^v>^<^^>>>^<v<v
><>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^<v>v^^<^^vv<
<<v<^>>^^^^>>>v^<>vvv^><v<<<>^^^vv^<vvv>^>v<^^^^v<>^>vvvv><>>v^<<^^^^^
^><^><>>><>^^<<^^v>>><^<v>^<vv>>v>>>^v><>^v><<<<v>>v<v<v>vvv>^<><<>^><
^>><>^v<><^vvv<^^<><v<<<<<><^v<<<><<<^^<v<^^^><^>>^<v^><<<^>>^v<v^v<v^
>^>>^v>vv>^<<^v<>><<><<v<<v><>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^
<><^^>^^^<><vvvvv^v<v<<>^v<v>v<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<>
^^>vv<^v^v<vv>^<><v<^v>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<><<v>
v^^>>><<^^<>>^v^<v^vv<>v^<<>^<^v^v><^<<<><<^<v><v<>vv>>v><v^<vv<>v^<<^"
}
#[test]
fn samples_part1() {
assert_eq!(10092, solve_part1(&input_generator(sample())));
}
#[test]
fn samples_part2() {
assert_eq!(9021, solve_part2(&input_generator2(sample())));
}
}