Skip to main content

aoc/year2021/
day20.rs

1//! # Trench Map
2//!
3//! This is a cellular automata problem, similar to Conway's Game of Life, except that the rules
4//! are encoded in the enhancement algorithm string, instead of being statically specified. Each
5//! round the initial square area of cells expands by at most one in each direction, so we can store
6//! the cell in a fixed-size array with enough space on either side to expand into.
7//!
8//! The interesting nuance is handling the edge cells when all 9 cells are empty (index 0) or all
9//! 9 cells are active (index 511). The sample data encodes a blank cell in both scenarios.
10//! My input encoded an active cell for index 0 and a blank cell for index 511, meaning that each
11//! turn the edge cells toggle from set to unset.
12//!
13//! The algorithm keeps track of the bounds of the expanding square and supplies a `default` value,
14//! that in the example case is always zero, but in the real data toggles between zero and one.
15//!
16//! A faster SIMD approach processes cells 16 at a time.
17use self::implementation::*;
18use crate::util::grid::*;
19use crate::util::point::*;
20
21type Input = (Vec<u8>, Grid<u8>);
22
23pub fn parse(input: &str) -> Input {
24    let (prefix, suffix) = input.split_once("\n\n").unwrap();
25
26    let algorithm = prefix.bytes().map(|b| u8::from(b == b'#')).collect();
27    let grid = Grid::parse(suffix);
28
29    (algorithm, grid)
30}
31
32pub fn part1(input: &Input) -> u32 {
33    enhance(input, 2)
34}
35
36pub fn part2(input: &Input) -> u32 {
37    enhance(input, 50)
38}
39
40#[cfg(not(feature = "simd"))]
41mod implementation {
42    use super::*;
43
44    pub(super) fn enhance(input: &Input, steps: i32) -> u32 {
45        let (algorithm, grid) = input;
46
47        // Offset the initial square by `steps` + 1 buffer cells in both dimensions.
48        // The square expands by at most one in each step so this is enough room to stay within
49        // bounds.
50        let extra = steps + 1;
51        let offset = Point::new(extra, extra);
52        let mut pixels = Grid::new(grid.width + 2 * extra, grid.height + 2 * extra, 0);
53
54        for point in grid.points() {
55            pixels[point + offset] = u8::from(grid[point] == b'#');
56        }
57
58        let mut next = pixels.clone();
59        let mut default = 0;
60
61        for step in 0..steps {
62            // Boundaries expand by one each turn.
63            let start = extra - step;
64            let end = extra + grid.width + step;
65
66            for y in (start - 1)..(end + 1) {
67                // If the pixel is within current bounds then return it, or else use the `default`
68                // edge value specified by the enhancement algorithm.
69                let helper = |sx, sy, shift| {
70                    let result = if sx < end && (start..end).contains(&sy) {
71                        pixels[Point::new(sx, sy)]
72                    } else {
73                        default
74                    };
75                    usize::from(result) << shift
76                };
77
78                // If the edge pixels are 1 then the initial edge will look like
79                // [##a]
80                // [##b]
81                // [##c]
82                // or 11a11b11c when encoded as an index.
83                let mut index = if default == 1 { 0b11011011 } else { 0b00000000 };
84
85                for x in (start - 1)..(end + 1) {
86                    // Keeps a sliding window of the index, updated as we evaluate the row from
87                    // left to right. Shift the index left by one each turn, updating the values
88                    // from the three new rightmost pixels entering the window.
89                    index = ((index << 1) & 0b110110110)
90                        + helper(x + 1, y - 1, 6)
91                        + helper(x + 1, y, 3)
92                        + helper(x + 1, y + 1, 0);
93
94                    next[Point::new(x, y)] = algorithm[index];
95                }
96            }
97
98            // Swap grids then calculate the next value for edge pixels beyond the boundary.
99            (pixels, next) = (next, pixels);
100            default = if default == 0 { algorithm[0] } else { algorithm[511] };
101        }
102
103        pixels.bytes.iter().map(|&b| u32::from(b)).sum()
104    }
105}
106
107#[cfg(feature = "simd")]
108mod implementation {
109    use std::simd::prelude::*;
110
111    use super::*;
112
113    const LANE_WIDTH: usize = 16;
114    type Vector = Simd<u16, LANE_WIDTH>;
115
116    pub(super) fn enhance(input: &Input, steps: i32) -> u32 {
117        let (algorithm, grid) = input;
118
119        // Offset the initial square by `steps` + 1 buffer cells in both dimensions.
120        // The square expands by at most one in each step so this is enough room to stay within
121        // bounds.
122        let extra = steps + 1;
123        let offset = Point::new(extra, extra);
124        let mut pixels =
125            Grid::new(grid.width + 2 * extra + LANE_WIDTH as i32, grid.height + 2 * extra, 0);
126
127        for point in grid.points() {
128            pixels[point + offset] = u8::from(grid[point] == b'#');
129        }
130
131        let mut next = pixels.clone();
132        let mut default = 0;
133
134        for step in 0..steps {
135            // Boundaries expand by one each turn.
136            let start = extra - 1 - step;
137            let end = extra + grid.width + 1 + step;
138
139            // Edge pixels on the infinite grid flip-flop between on and off.
140            for y in (start - 1)..(end + 1) {
141                pixels[Point::new(start - 1, y)] = default;
142                pixels[Point::new(start, y)] = default;
143                pixels[Point::new(end - 1, y)] = default;
144                pixels[Point::new(end, y)] = default;
145            }
146
147            for x in (start..end).step_by(LANE_WIDTH) {
148                let edge = Simd::splat(if default == 0 { 0b000 } else { 0b111 });
149                let mut above = edge;
150                let mut row = edge;
151
152                for y in start..end {
153                    let below = if y < end - 2 { from_grid(&pixels, x, y + 1) } else { edge };
154
155                    let indices = (above << 6) | (row << 3) | below;
156                    above = row;
157                    row = below;
158
159                    let base = (pixels.width * y + x) as usize;
160                    for (i, j) in indices.to_array().into_iter().enumerate() {
161                        next.bytes[base + i] = algorithm[usize::from(j)];
162                    }
163                }
164            }
165
166            // Swap grids then calculate the next value for edge pixels beyond the boundary.
167            (pixels, next) = (next, pixels);
168            default = if default == 0 { algorithm[0] } else { algorithm[511] };
169        }
170
171        // Only count pixels inside the boundary.
172        let end = extra + grid.width + 1 + steps;
173        let mut result = 0;
174
175        for y in 1..end - 1 {
176            for x in 1..end - 1 {
177                result += u32::from(pixels[Point::new(x, y)]);
178            }
179        }
180
181        result
182    }
183
184    #[inline]
185    fn from_grid(grid: &Grid<u8>, x: i32, y: i32) -> Vector {
186        let index = (grid.width * y + x) as usize;
187
188        let row = Simd::from_slice(&grid.bytes[index..]);
189        let left = row.shift_elements_right::<1>(grid[Point::new(x - 1, y)]);
190        let right = row.shift_elements_left::<1>(grid[Point::new(x + LANE_WIDTH as i32, y)]);
191
192        let result = (left << 2) | (row << 1) | right;
193        result.cast()
194    }
195}