DEVELOPMENT ENVIRONMENT

~liljamo/aoc2024

ref: d978ab7908e2a7fd929ea3144d9ff925f6400e15 aoc2024/src/day15/part1.rs -rw-r--r-- 4.9 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
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)]
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::Wall),
                    'O' => row.push(Tile::Box),
                    '@' => {
                        row.push(Tile::Empty);
                        robot = Some(Pos { x, 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 => {
                if self.move_box(p, direction) {
                    self.robot.r#move(direction);
                }
            }
        }
    }

    fn move_box(&mut self, our_p: Pos, direction: &Direction) -> bool {
        let (tile, p) = self.get_tile_in_direction(our_p.x, our_p.y, direction);
        match tile {
            Tile::Empty => {
                self.tiles[our_p.y][our_p.x] = Tile::Empty;
                self.tiles[p.y][p.x] = Tile::Box;
                true
            }
            Tile::Wall => false,
            Tile::Box => {
                if self.move_box(p.clone(), direction) {
                    self.tiles[our_p.y][our_p.x] = Tile::Empty;
                    self.tiles[p.y][p.x] = Tile::Box;
                    true
                } else {
                    false
                }
            }
        }
    }

    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!();
        }
    }
}

enum Tile {
    Empty,
    Wall,
    Box,
}

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 => write!(f, "O"),
        }
    }
}

pub fn part_one(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);
    for direction in movements {
        wh.move_robot(&direction);
    }

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

    Ok(answer)
}