summaryrefslogtreecommitdiff
path: root/2024_rust/src/bin/day6.rs
blob: d8a4580c09a42997d3fdbb46ae38af7eee9837ee (plain) (blame)
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
use aoc2024::matrix;
use std::collections::{HashMap, HashSet};
use std::fmt;

#[derive(Clone, Copy, PartialEq, Eq, Hash)]
enum Direction {
    Up,
    Right,
    Down,
    Left,
}
use Direction::*;

impl Direction {
    fn rotate(self) -> Self {
        match self {
            Up => Right,
            Right => Down,
            Down => Left,
            Left => Up,
        }
    }
}

#[derive(Clone)]
enum Dot {
    Empty,
    Obstacle,
    Visited,
    Guard(Direction),
}
use Dot::*;

impl fmt::Display for Dot {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let ch = match self {
            Empty => ".",
            Obstacle => "#",
            Visited => "X",
            Guard(Up) => "^",
            Guard(Right) => ">",
            Guard(Down) => "v",
            Guard(Left) => "<",
        };
        write!(f, "{}", ch)
    }
}

impl Dot {
    fn parse(c: char) -> Dot {
        match c {
            '.' => Empty,
            '#' => Obstacle,
            'X' => Visited,
            '^' => Guard(Up),
            '>' => Guard(Right),
            'v' => Guard(Down),
            '<' => Guard(Left),
            _ => panic!("Invalid input"),
        }
    }
}

#[derive(Clone)]
struct M {
    matrix: matrix::Matrix<Dot>,
    guard: matrix::Pos,
    visited: HashMap<matrix::Pos, HashSet<Direction>>,
}

impl M {
    fn new(text: &str) -> Self {
        let matrix = matrix::Matrix::new(text, Dot::parse);
        let mut guard = (0, 0);
        let mut visited = HashMap::new();
        for i in 0..matrix.limit.0 {
            for j in 0..matrix.limit.1 {
                if let Guard(dir) = matrix.get((i, j)) {
                    let mut dirhs = HashSet::new();
                    dirhs.insert(*dir);
                    visited.insert(guard, dirhs);
                    guard = (i, j);
                }
            }
        }
        M {
            matrix,
            guard,
            visited,
        }
    }
}

#[derive(Debug)]
enum SimResult {
    OutOfBounds,
    Loop,
}

impl M {
    fn step(&mut self) -> Option<SimResult> {
        let M {
            matrix,
            guard,
            visited,
        } = self;

        // Compute guard's next position
        let Guard(direction) = matrix.get(*guard) else {
            panic!("Impossible: {self}")
        };
        let newpos: (usize, usize) = match direction {
            Up if guard.0 > 0 => (guard.0 - 1, guard.1),
            Right if guard.1 < matrix.limit.1 - 1 => (guard.0, guard.1 + 1),
            Down if guard.0 < matrix.limit.0 - 1 => (guard.0 + 1, guard.1),
            Left if guard.1 > 0 => (guard.0, guard.1 - 1),
            _ => return Some(SimResult::OutOfBounds),
        };
        match (matrix.get(newpos), visited.get(guard)) {
            (Visited, Some(vs)) if vs.contains(direction) => return Some(SimResult::Loop),
            (Empty | Visited, _) => {
                let d = *direction;
                matrix.set(newpos, Guard(d));
                matrix.set(*guard, Visited);
                let hs = visited.entry(*guard).or_insert(HashSet::new());
                hs.insert(d);
                *guard = newpos;
            }
            (Obstacle, _) => {
                matrix.set(*guard, Guard(direction.rotate()));
            }
            _ => (),
        };
        // println!("{self}");
        None
    }

    fn step_forever(&mut self) -> SimResult {
        loop {
            if let Some(res) = self.step() { return res }
        }
    }

    fn count_visited(&self) -> u32 {
        let mut result: u32 = 0;
        let M { matrix, .. } = self;
        for i in 0..matrix.limit.0 {
            for j in 0..matrix.limit.1 {
                match matrix.get((i, j)) {
                    Visited | Guard(_) => result += 1,
                    _ => (),
                }
            }
        }
        result
    }
}

impl fmt::Display for M {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // write!(f, "{}[2J", 27 as char)?;
        write!(f, "{}", self.matrix)?;
        write!(f, "[Guard position: {:?}]", self.guard)
    }
}

fn p1(input: &str) -> String {
    let mut m: M = M::new(input);
    println!("{m}");
    println!("Result: {:?}", m.step_forever());
    println!("{m}");
    let result = m.count_visited();
    result.to_string()
}

fn count_loops(m: M) -> u32 {
    let mut result = 0;
    // let mut simulations = 0;
    for i in 0..m.matrix.limit.0 {
        for j in 0..m.matrix.limit.1 {
            if let Empty = m.matrix.get((i, j)) {
                // simulations += 1;
                let mut m1 = m.clone();
                m1.matrix.set((i, j), Obstacle);
                // println!("Simulation {simulations} @ ({i},{j}) ({result})...");
                // println!("{m1}");
                if let SimResult::Loop = m1.step_forever() {
                    result += 1;
                }
            }
        }
    }
    result
}

fn p2(input: &str) -> String {
    let m: M = M::new(input);
    let result = count_loops(m);
    result.to_string()
}

fn main() {
    aoc2024::run_day("6", p1, p2);
}