advent_of_code/year2023/
day10.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
use crate::common::array_deque::ArrayDeque;
use crate::common::u256::U256;
use crate::input::{on_error, Input};

pub fn solve(input: &Input) -> Result<u64, String> {
    const MAX_GRID_SIZE: usize = 150;
    const MAX_STACK_SIZE: usize = 4;

    let map = Map::parse(input.text.trim().as_bytes())?;
    if map.num_rows > MAX_GRID_SIZE || map.num_cols > MAX_GRID_SIZE {
        return Err(format!("Invalid input - max grid size is {MAX_GRID_SIZE}"));
    }

    let start_idx = map
        .bytes
        .iter()
        .enumerate()
        .find_map(|(idx, &b)| (b == b'S').then_some(idx))
        .ok_or_else(on_error)?;
    let (start_x, start_y) = map.idx_to_xy(start_idx);

    let mut visited_bitmask = [U256::default(); MAX_GRID_SIZE];
    visited_bitmask[start_y].set_bit(start_x);

    let mut to_visit = ArrayDeque::<MAX_STACK_SIZE, (usize, u64)>::new();
    to_visit.push_back((start_idx, 0))?;

    let mut max_distance = 0;

    while let Some((idx, distance)) = to_visit.pop_front() {
        let (x, y) = map.idx_to_xy(idx);
        let from = map.bytes[idx];
        for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)] {
            let (nx, ny) = (x as i32 + dx, y as i32 + dy);
            if nx >= 0 && nx < map.num_cols as i32 && ny >= 0 && ny < map.num_rows as i32 {
                let (nx, ny) = (nx as usize, ny as usize);
                let to = map.get(nx, ny);
                if matches!(
                    (from, to, dx, dy),
                    (b'S' | b'-' | b'L' | b'F', b'-' | b'J' | b'7', 1, 0)
                        | (b'S' | b'-' | b'J' | b'7', b'-' | b'L' | b'F', -1, 0)
                        | (b'S' | b'|' | b'F' | b'7', b'|' | b'L' | b'J', 0, 1)
                        | (b'S' | b'|' | b'L' | b'J', b'|' | b'F' | b'7', 0, -1)
                ) && !visited_bitmask[ny].is_bit_set(nx)
                {
                    visited_bitmask[ny].set_bit(nx);
                    max_distance = distance + 1;
                    to_visit.push_back((map.xy_to_idx(nx, ny), max_distance))?;
                }
            }
        }
    }

    if input.is_part_one() {
        return Ok(max_distance);
    }

    let mut inside_loop_count = 0;
    for (y, bitset) in visited_bitmask.iter_mut().enumerate() {
        let mut inside_loop = false;
        for x in 0..map.num_cols {
            if bitset.is_bit_set(x) {
                let b = map.get(x, y);
                if matches!(b, b'|' | b'L' | b'J')
                    || (b == b'S' && (y != 0 && matches!(map.get(x, y - 1), b'|' | b'7' | b'F')))
                {
                    inside_loop = !inside_loop;
                }
            } else if inside_loop {
                inside_loop_count += 1;
            }
        }
    }
    Ok(inside_loop_count)
}

struct Map<'a> {
    bytes: &'a [u8],
    num_rows: usize,
    num_cols: usize,
}

impl<'a> Map<'a> {
    fn parse(bytes: &'a [u8]) -> Result<Self, String> {
        let num_cols = bytes
            .iter()
            .position(|&b| b == b'\n')
            .ok_or_else(on_error)?;
        if (bytes.len() + 1) % (num_cols + 1) != 0 {
            return Err(on_error());
        }
        let num_rows = (bytes.len() + 1) / (num_cols + 1);
        Ok(Self {
            bytes,
            num_rows,
            num_cols,
        })
    }

    const fn idx_to_xy(&self, idx: usize) -> (usize, usize) {
        let y = idx / (self.num_cols + 1);
        let x = idx - y * (self.num_cols + 1);
        (x, y)
    }

    const fn xy_to_idx(&self, x: usize, y: usize) -> usize {
        (self.num_cols + 1) * y + x
    }

    const fn get(&self, x: usize, y: usize) -> u8 {
        self.bytes[self.xy_to_idx(x, y)]
    }
}

#[test]
pub fn tests() {
    use crate::input::{test_part_one_no_allocations, test_part_two_no_allocations};

    let test_input = ".....
.S-7.
.|.|.
.L-J.
.....";
    test_part_one_no_allocations!(test_input => 4);

    let test_input = "..F7.
.FJ|.
SJ.L7
|F--J
LJ...";
    test_part_one_no_allocations!(test_input => 8);

    let test_input = "...........
.S-------7.
.|F-----7|.
.||.....||.
.||.....||.
.|L-7.F-J|.
.|..|.|..|.
.L--J.L--J.
...........";
    test_part_two_no_allocations!(test_input => 4);

    let test_input = "..........
.S------7.
.|F----7|.
.||....||.
.||....||.
.|L-7F-J|.
.|..||..|.
.L--JL--J.
..........";
    test_part_two_no_allocations!(test_input => 4);

    let real_input = include_str!("day10_input.txt");
    test_part_one_no_allocations!(real_input => 6875);
    test_part_two_no_allocations!(real_input => 471);
}