year2024/
day06.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
use utils::grid;
use utils::point::Point2D;
use utils::prelude::*;

/// Finding obstructions to cause infinite loops.
#[derive(Clone, Debug)]
pub struct Day06 {
    pub rows: usize,
    pub cols: usize,
    pub grid: Vec<u8>,
    pub start: Point2D<usize>,
}

const DIRECTIONS: [Point2D<isize>; 4] = [Point2D::DOWN, Point2D::RIGHT, Point2D::UP, Point2D::LEFT];

impl Day06 {
    pub fn new(input: &str, _: InputType) -> Result<Self, InputError> {
        let (rows, cols, mut grid) = grid::from_str(input, |b| match b {
            b'.' | b'#' | b'^' => Some(b),
            _ => None,
        })?;

        let start_index = grid.iter().position(|&c| c == b'^').unwrap();
        let start = Point2D::new(start_index % cols, start_index / cols);
        grid[start_index] = b'.';

        Ok(Self {
            rows,
            cols,
            grid,
            start,
        })
    }

    #[must_use]
    pub fn part1(&self) -> usize {
        let mut pos = self.start;
        let mut dir = 0;
        let mut visited = vec![false; self.grid.len()];
        loop {
            visited[pos.y * self.cols + pos.x] = true;

            let next = pos.wrapping_add_signed(DIRECTIONS[dir]);
            if next.x >= self.cols || next.y >= self.rows {
                break;
            }
            if self.grid[next.y * self.cols + next.x] == b'#' {
                dir = (dir + 1) % 4;
            } else {
                pos = next;
            }
        }
        visited.iter().filter(|&&c| c).count()
    }

    #[must_use]
    pub fn part2(&self) -> usize {
        let mut pos = self.start;
        let mut dir = 0;
        let mut visited = vec![0u8; self.grid.len()];
        let mut obstructions = vec![false; self.grid.len()];
        let mut cached_step_counts = vec![[0; 4]; self.grid.len()];
        loop {
            visited[pos.y * self.cols + pos.x] |= 1 << dir;

            let next = pos.wrapping_add_signed(DIRECTIONS[dir]);
            if next.x >= self.cols || next.y >= self.rows {
                break;
            }

            if self.grid[next.y * self.cols + next.x] == b'#' {
                dir = (dir + 1) % 4;
            } else {
                if !obstructions[next.y * self.cols + next.x]
                    && visited[next.y * self.cols + next.x] == 0
                    && self.check_cycle(next, pos, dir, &visited, &mut cached_step_counts)
                {
                    obstructions[next.y * self.cols + next.x] = true;
                }

                pos = next;
            }
        }
        obstructions.iter().filter(|&&c| c).count()
    }

    // Combination of two algorithms starting from the current position:
    // 1) Checking against previously visited states/if position leaves grid
    // 2) The start of Brent's algorithm for cycle detection as used in 2017 day 6
    // This also avoids allocating/zeroing/copying a new visited vec
    fn check_cycle(
        &self,
        obstruction: Point2D<usize>,
        pos: Point2D<usize>,
        dir: usize,
        visited: &[u8],
        cache: &mut [[isize; 4]],
    ) -> bool {
        let (mut power, mut lambda) = (1, 1);
        let (mut tortoise_pos, mut tortoise_dir) = (pos, dir);
        let (mut hare_pos, mut hare_dir) = (pos, dir);

        loop {
            if power == lambda {
                tortoise_pos = hare_pos;
                tortoise_dir = hare_dir;
                power *= 2;
                lambda = 0;
            }
            lambda += 1;

            // Advance to the next obstruction
            if hare_pos.x == obstruction.x || hare_pos.y == obstruction.y {
                // On the same X or Y line as the temporary obstruction, loop without caching
                loop {
                    let next = hare_pos.wrapping_add_signed(DIRECTIONS[hare_dir]);
                    if next.x >= self.cols || next.y >= self.rows {
                        // No cycle, hare has left the grid
                        return false;
                    }
                    if self.grid[next.y * self.cols + next.x] == b'#' || next == obstruction {
                        break;
                    }
                    hare_pos = next;
                }
            } else {
                // Temporary obstruction can be ignored as not on the same X or Y line as it
                let cached_count = &mut cache[hare_pos.y * self.cols + hare_pos.x][hare_dir];
                if *cached_count > 0 {
                    // Advanced by the previously cached count
                    hare_pos = hare_pos.wrapping_add_signed(DIRECTIONS[hare_dir] * *cached_count);
                    if hare_pos.x >= self.cols || hare_pos.y >= self.rows {
                        // No cycle, hare has left the grid
                        return false;
                    }
                } else {
                    // Loop, caching the step count until the next obstruction
                    loop {
                        let next = hare_pos.wrapping_add_signed(DIRECTIONS[hare_dir]);
                        if next.x >= self.cols || next.y >= self.rows {
                            // No cycle, hare has left the grid
                            *cached_count += 1;
                            return false;
                        }
                        if self.grid[next.y * self.cols + next.x] == b'#' {
                            break;
                        }
                        hare_pos = next;
                        *cached_count += 1;
                    }
                }
            }

            hare_dir = (hare_dir + 1) % 4;

            if visited[hare_pos.y * self.cols + hare_pos.x] & (1 << hare_dir) != 0 {
                // Cycle, hare has reached a previous state from before adding the obstacle
                return true;
            }
            if hare_pos == tortoise_pos && hare_dir == tortoise_dir {
                // Cycle, hare and tortoise are in the same state
                return true;
            }
        }
    }
}

examples!(Day06 -> (usize, usize) [
    {file: "day06_example0.txt", part1: 41, part2: 6},
]);