DEVELOPMENT ENVIRONMENT

~liljamo/aoc2024

ref: d978ab7908e2a7fd929ea3144d9ff925f6400e15 aoc2024/src/day15/part2.rs -rw-r--r-- 9.1 KiB
d978ab79Jonni Liljamo feat: day15 partly a month ago
                                                                                
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
use std::{
    fs::File,
    io::{BufRead, BufReader},
    path::Path,
};

#[derive(Debug)]
enum Direction {
    North,
    East,
    South,
    West,
}

impl Direction {
    fn from_c(c: char) -> Self {
        match c {
            '^' => Direction::North,
            '>' => Direction::East,
            'v' => Direction::South,
            '<' => Direction::West,
            _ => unreachable!(),
        }
    }
}

#[derive(Clone, Debug)]
struct Pos {
    x: usize,
    y: usize,
}

impl Pos {
    fn r#move(&mut self, direction: &Direction) {
        match direction {
            Direction::North => self.y -= 1,
            Direction::East => self.x += 1,
            Direction::South => self.y += 1,
            Direction::West => self.x -= 1,
        }
    }
}

struct Warehouse {
    robot: Pos,
    tiles: Vec<Vec<Tile>>,
}

impl Warehouse {
    fn from_lines(lines: &[String]) -> Self {
        let mut tiles = vec![];
        let mut robot = None;
        for (y, line) in lines.iter().enumerate() {
            let mut row = vec![];
            for (x, c) in line.chars().enumerate() {
                match c {
                    '.' => {
                        row.push(Tile::Empty);
                        row.push(Tile::Empty);
                    }
                    '#' => {
                        row.push(Tile::Wall);
                        row.push(Tile::Wall);
                    }
                    'O' => {
                        row.push(Tile::Box(Side::Left));
                        row.push(Tile::Box(Side::Right));
                    }
                    '@' => {
                        row.push(Tile::Empty);
                        row.push(Tile::Empty);
                        robot = Some(Pos { x: x * 2, y });
                    }
                    _ => unreachable!(),
                }
            }
            tiles.push(row);
        }
        Self {
            robot: robot.unwrap(),
            tiles,
        }
    }

    fn get_tile_in_direction(&self, x: usize, y: usize, direction: &Direction) -> (&Tile, Pos) {
        match direction {
            Direction::North => (&self.tiles[y - 1][x], Pos { x, y: y - 1 }),
            Direction::East => (&self.tiles[y][x + 1], Pos { x: x + 1, y }),
            Direction::South => (&self.tiles[y + 1][x], Pos { x, y: y + 1 }),
            Direction::West => (&self.tiles[y][x - 1], Pos { x: x - 1, y }),
        }
    }

    fn move_robot(&mut self, direction: &Direction) {
        let (tile, p) = self.get_tile_in_direction(self.robot.x, self.robot.y, direction);
        match tile {
            Tile::Empty => self.robot.r#move(direction),
            Tile::Wall => {}
            Tile::Box(_side) => {
                if self.move_box(*tile, p, direction, false) {
                    self.robot.r#move(direction);
                }
            }
        }
    }

    fn move_box(
        &mut self,
        us: Tile,
        our_p: Pos,
        direction: &Direction,
        is_other_side: bool,
    ) -> bool {
        match direction {
            Direction::East | Direction::West => {
                let (tile, p) = self.get_tile_in_direction(our_p.x, our_p.y, direction);
                if match tile {
                    Tile::Empty => true,
                    Tile::Wall => false,
                    Tile::Box(_) => self.move_box(*tile, p.clone(), direction, false),
                } {
                    self.tiles[p.y][p.x] = self.tiles[our_p.y][our_p.x];
                    self.tiles[our_p.y][our_p.x] = Tile::Empty;
                    true
                } else {
                    false
                }
            }
            Direction::North | Direction::South => {
                let (tile, p) = self.get_tile_in_direction(our_p.x, our_p.y, direction);
                if is_other_side {
                    if match tile {
                        Tile::Empty => true,
                        Tile::Wall => false,
                        Tile::Box(_) => self.move_box(*tile, p.clone(), direction, false),
                    } {
                        self.tiles[p.y][p.x] = self.tiles[our_p.y][our_p.x];
                        self.tiles[our_p.y][our_p.x] = Tile::Empty;
                        return true;
                    } else {
                        return false;
                    }
                }
                match tile {
                    Tile::Empty => {
                        if let Tile::Box(side) = us {
                            let other_p = match side {
                                Side::Left => Pos {
                                    x: our_p.x + 1,
                                    y: our_p.y,
                                },
                                Side::Right => Pos {
                                    x: our_p.x - 1,
                                    y: our_p.y,
                                },
                            };
                            if self.move_box(
                                self.tiles[other_p.y][other_p.x],
                                other_p,
                                direction,
                                true,
                            ) {
                                self.tiles[p.y][p.x] = self.tiles[our_p.y][our_p.x];
                                self.tiles[our_p.y][our_p.x] = Tile::Empty;
                                true
                            } else {
                                false
                            }
                        } else {
                            unreachable!();
                        }
                    }
                    Tile::Wall => false,
                    Tile::Box(_) => {
                        if !self.move_box(*tile, p.clone(), direction, false) {
                            return false;
                        }
                        if let Tile::Box(side) = us {
                            let other_p = match side {
                                Side::Left => Pos {
                                    x: our_p.x + 1,
                                    y: our_p.y,
                                },
                                Side::Right => Pos {
                                    x: our_p.x - 1,
                                    y: our_p.y,
                                },
                            };
                            if self.move_box(
                                self.tiles[other_p.y][other_p.x],
                                other_p,
                                direction,
                                true,
                            ) {
                                self.tiles[p.y][p.x] = self.tiles[our_p.y][our_p.x];
                                self.tiles[our_p.y][our_p.x] = Tile::Empty;
                                true
                            } else {
                                false
                            }
                        } else {
                            unreachable!();
                        }
                    }
                }
            }
        }
    }

    fn _print(&self) {
        for (y, row) in self.tiles.iter().enumerate() {
            for (x, tile) in row.iter().enumerate() {
                if y == self.robot.y && x == self.robot.x {
                    print!("@");
                } else {
                    print!("{}", tile);
                }
            }
            println!();
        }
    }
}

#[derive(Clone, Copy, Debug)]
enum Tile {
    Empty,
    Wall,
    Box(Side),
}

#[derive(Clone, Copy, Debug, PartialEq)]
enum Side {
    Left,
    Right,
}

impl std::fmt::Display for Tile {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Tile::Empty => write!(f, "."),
            Tile::Wall => write!(f, "#"),
            Tile::Box(side) => match side {
                Side::Left => write!(f, "["),
                Side::Right => write!(f, "]"),
            },
        }
    }
}

pub fn part_two(input: &Path) -> anyhow::Result<usize> {
    let reader = BufReader::new(File::open(input)?);

    let mut map_lines: Vec<String> = vec![];
    let mut movements: Vec<Direction> = vec![];
    let mut split = false;
    for line in reader.lines() {
        let line = line?;
        if line.is_empty() {
            split = true;
            continue;
        }
        if split {
            movements.append(
                &mut line
                    .trim()
                    .chars()
                    .map(|c| -> Direction { Direction::from_c(c) })
                    .collect::<Vec<Direction>>(),
            );
        } else {
            map_lines.push(line);
        }
    }
    let mut wh = Warehouse::from_lines(&map_lines);
    wh._print();
    for direction in movements {
        dbg!(&direction);
        wh.move_robot(&direction);
        wh._print();
        println!();
    }

    let mut answer = 0;
    for (y, row) in wh.tiles.iter().enumerate() {
        for (x, tile) in row.iter().enumerate() {
            if let Tile::Box(side) = tile {
                if *side == Side::Left {
                    answer += 100 * y + x;
                }
            }
        }
    }

    Ok(answer)
}