DEVELOPMENT ENVIRONMENT

~liljamo/aoc2024

ref: 9bedcc71e44c678525219d72ec3a4b18d4687983 aoc2024/src/day6/mod.rs -rw-r--r-- 5.9 KiB
9bedcc71Jonni Liljamo feat: day8 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
use std::{
    fs::File,
    io::{BufRead, BufReader},
    path::Path,
};

pub fn solve(input: &Path) -> anyhow::Result<()> {
    println!("part one: {}", part_one(input)?);
    println!("part two: {}", part_two(input)?);

    Ok(())
}

#[derive(Default, Clone)]
struct Pos {
    x: usize,
    y: usize,
    visited: bool,
    obstacle: bool,
}

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

impl Guard {
    fn turn(&mut self) {
        match self.direction {
            Direction::North => self.direction = Direction::East,
            Direction::East => self.direction = Direction::South,
            Direction::South => self.direction = Direction::West,
            Direction::West => self.direction = Direction::North,
        }
    }

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

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

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

    let mut map: Vec<Vec<Pos>> = vec![];
    let mut guard: Option<Guard> = None;
    for (y, line) in reader.lines().enumerate() {
        let mut row = vec![];
        for (x, c) in line?.char_indices() {
            match c {
                '.' => row.push(Pos {
                    x,
                    y,
                    ..Default::default()
                }),
                '#' => row.push(Pos {
                    x,
                    y,
                    obstacle: true,
                    ..Default::default()
                }),
                '^' => {
                    row.push(Pos {
                        x,
                        y,
                        visited: true,
                        ..Default::default()
                    });
                    guard = Some(Guard {
                        x,
                        y,
                        direction: Direction::North,
                    });
                }
                _ => panic!("invalid map"),
            }
        }
        map.push(row);
    }
    let mut guard = guard.unwrap();

    loop {
        //print_map(&map);
        if let Some(in_front) = get_in_front(&guard, &mut map) {
            if in_front.obstacle {
                guard.turn();
            } else {
                in_front.visited = true;
                guard.move_forward();
            }
        } else {
            break;
        }
        //std::thread::sleep(std::time::Duration::from_millis(50));
    }

    //print_map(&map);

    Ok(map.iter().flatten().filter(|p| p.visited).count() as i32)
}

fn get_in_front<'a>(guard: &'a Guard, map: &'a mut [Vec<Pos>]) -> Option<&'a mut Pos> {
    match guard.direction {
        Direction::North => match map.get_mut(if guard.y == 0 {
            return None;
        } else {
            guard.y - 1
        }) {
            Some(row) => row.get_mut(guard.x),
            None => None,
        },
        Direction::East => match map.get_mut(guard.y) {
            Some(row) => row.get_mut(guard.x + 1),
            None => None,
        },
        Direction::South => match map.get_mut(guard.y + 1) {
            Some(row) => row.get_mut(guard.x),
            None => None,
        },
        Direction::West => match map.get_mut(guard.y) {
            Some(row) => row.get_mut(if guard.x == 0 {
                return None;
            } else {
                guard.x - 1
            }),
            None => None,
        },
    }
}

fn print_map(map: &[Vec<Pos>]) {
    for row in map {
        for pos in row {
            if pos.obstacle {
                print!("# ");
            } else if pos.visited {
                print!("X ");
            } else {
                print!(". ");
            }
        }
        println!();
    }
}

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

    let mut map: Vec<Vec<Pos>> = vec![];
    let mut guard: Option<Guard> = None;
    for (y, line) in reader.lines().enumerate() {
        let mut row = vec![];
        for (x, c) in line?.char_indices() {
            match c {
                '.' => row.push(Pos {
                    x,
                    y,
                    ..Default::default()
                }),
                '#' => row.push(Pos {
                    x,
                    y,
                    obstacle: true,
                    ..Default::default()
                }),
                '^' => {
                    row.push(Pos {
                        x,
                        y,
                        visited: true,
                        ..Default::default()
                    });
                    guard = Some(Guard {
                        x,
                        y,
                        direction: Direction::North,
                    });
                }
                _ => panic!("invalid map"),
            }
        }
        map.push(row);
    }
    let guard = guard.unwrap();

    let mut block_positions = 0;
    for pos in map.iter().flatten() {
        let mut guard = guard.clone();
        let mut modified_map = map.clone();
        modified_map[pos.y][pos.x].obstacle = true;
        let start_time = std::time::Instant::now();
        loop {
            if let Some(in_front) = get_in_front(&guard, &mut modified_map) {
                if in_front.obstacle {
                    guard.turn();
                } else {
                    in_front.visited = true;
                    guard.move_forward();
                }
            } else {
                break;
            }

            if start_time.elapsed().as_millis() >= 1 {
                block_positions += 1;
                break;
            }
        }
    }

    Ok(block_positions)
}