Skip to main content

aoc/year2020/
day11.rs

1//! # Seating System
2//!
3//! Cellular automata are hard to speed up due to the need to check all neighbors each iteration.
4//! For both parts we minimize expensive memory allocation by creating only two temporary buffers
5//! then swapping between them each turn, a similar approach to double buffering.
6//!
7//! For part two we can further optimize by precalculating the locations of the nearest visible
8//! seats only once then reusing that information for each step.
9//!
10//! The SIMD version speeds things up by calculating 32 lanes at a time.
11use self::implementation::*;
12use crate::util::grid::*;
13use crate::util::point::*;
14
15const SEAT: u8 = b'L';
16
17pub fn parse(input: &str) -> Grid<u8> {
18    // A newline border allows us to avoid boundary checks.
19    Grid::parse_with_border(input)
20}
21
22pub fn part1(input: &Grid<u8>) -> u32 {
23    simulate(input, false, 4)
24}
25
26pub fn part2(input: &Grid<u8>) -> u32 {
27    simulate(input, true, 5)
28}
29
30#[cfg(not(feature = "simd"))]
31mod implementation {
32    use super::*;
33
34    const FLOOR: u8 = b'.';
35
36    struct Seat {
37        point: Point,
38        neighbors: [Point; 8],
39    }
40
41    pub(super) fn simulate(input: &Grid<u8>, part_two: bool, limit: u8) -> u32 {
42        let mut seats = Vec::new();
43
44        for point in input.points() {
45            if input[point] != SEAT {
46                continue;
47            }
48
49            // Part one considers only the adjacent square. Part two skips over any
50            // floor until reaching the first visible seat or the edge of the grid.
51            // Non-seats map to the origin, which is never occupied so always adds zero.
52            let neighbors = DIAGONAL.map(|direction| {
53                let mut next = point + direction;
54                while part_two && input[next] == FLOOR {
55                    next += direction;
56                }
57                if input[next] == SEAT { next } else { ORIGIN }
58            });
59
60            seats.push(Seat { point, neighbors });
61        }
62
63        let mut current = input.same_size_with(0);
64        let mut next = input.same_size_with(0);
65
66        loop {
67            for seat in &seats {
68                let total: u8 = seat.neighbors.iter().map(|&i| current[i]).sum();
69
70                next[seat.point] = if current[seat.point] == 0 {
71                    u8::from(total == 0)
72                } else {
73                    u8::from(total < limit)
74                };
75            }
76
77            (current, next) = (next, current);
78            if current == next {
79                return current.bytes.iter().map(|&n| u32::from(n)).sum();
80            }
81        }
82    }
83}
84
85#[cfg(feature = "simd")]
86mod implementation {
87    use std::simd::prelude::*;
88
89    use super::*;
90
91    const LANE_WIDTH: usize = 32;
92    type Vector = Simd<u8, LANE_WIDTH>;
93
94    pub(super) fn simulate(input: &Grid<u8>, part_two: bool, limit: u8) -> u32 {
95        // Input grid is taller than it is wide. To make efficient use of the wide SIMD operations:
96        // * Change the existing newline border to empty, but keep it to eliminate bounds checking.
97        // * Transpose the input grid to make it wider than it is tall.
98        // * Round width up to next multiple of LANE_WIDTH.
99        let width = 2 + (input.height as usize - 2).next_multiple_of(LANE_WIDTH) as i32;
100        let height = 1 + input.width;
101        let mut grid = Grid::new(width, height, 0);
102
103        for from in input.points() {
104            let to = Point::new(from.y, from.x);
105            grid[to] = u8::from(input[from] == SEAT);
106        }
107
108        // Build a list of seats that are non-adjacent but visible to each other.
109        let mut visible = Vec::new();
110
111        if part_two {
112            for from in grid.points() {
113                if grid[from] == 0 {
114                    continue;
115                }
116
117                for direction in DIAGONAL {
118                    if grid[from + direction] == 1 {
119                        continue;
120                    }
121
122                    let mut to = from + direction * 2;
123                    while grid.contains(to) {
124                        if grid[to] == 1 {
125                            visible.push((from, to));
126                            break;
127                        }
128                        to += direction;
129                    }
130                }
131            }
132        }
133
134        // Common constants.
135        let zero = Simd::splat(0);
136        let one = Simd::splat(1);
137        let limit = Simd::splat(limit);
138
139        let mut current = grid.same_size_with(0);
140        let mut next = grid.same_size_with(0);
141        let mut extra = grid.same_size_with(0);
142
143        loop {
144            // Add any non-adjacent seats that are visible to the total.
145            if part_two {
146                extra.bytes.fill(0);
147                for &(from, to) in &visible {
148                    extra[to] += current[from];
149                }
150            }
151
152            // Process grid column by column using wide SIMD vectors.
153            for x in (1..width - 1).step_by(LANE_WIDTH) {
154                let mut above = horizontal_neighbors(&current, x, 0);
155                let mut row = horizontal_neighbors(&current, x, 1);
156
157                for y in 1..height - 1 {
158                    let index = (width * y + x) as usize;
159                    let seats = Simd::from_slice(&grid.bytes[index..]);
160                    let occupied = Simd::from_slice(&current.bytes[index..]);
161                    let extra = Simd::from_slice(&extra.bytes[index..]);
162
163                    let below = horizontal_neighbors(&current, x, y + 1);
164                    let total = row + above + below + extra;
165                    above = row;
166                    row = below;
167
168                    // Empty to occupied.
169                    let first = total.simd_eq(zero).select(one, zero);
170                    // Occupied to empty.
171                    let second = total.simd_le(limit).select(occupied, zero);
172                    // Nobody sits on the floor.
173                    let result = (first + second) & seats;
174
175                    result.copy_to_slice(&mut next.bytes[index..]);
176                }
177            }
178
179            (current, next) = (next, current);
180            if current == next {
181                return current.bytes.iter().map(|&b| u32::from(b)).sum();
182            }
183        }
184    }
185
186    /// Create SIMD vector of the sum of left, right and center lanes.
187    #[inline]
188    fn horizontal_neighbors(grid: &Grid<u8>, x: i32, y: i32) -> Vector {
189        let index = (grid.width * y + x) as usize;
190
191        let center = Simd::from_slice(&grid.bytes[index..]);
192        let left = center.shift_elements_left::<1>(grid.bytes[index + LANE_WIDTH]);
193        let right = center.shift_elements_right::<1>(grid.bytes[index - 1]);
194
195        center + left + right
196    }
197}