Skip to main content

aoc/year2020/
day17.rs

1//! # Conway Cubes
2//!
3//! Solving this problem reveals an interesting insight that the active cells are very sparse.
4//! Of the total possible volume of the cube formed by the maximum extents in part one, only
5//! roughly 8% is active and of the hypercube from part two only 3% is active for my input.
6//!
7//! To speed things up our high-level strategy will flip from a "pull" model where we check the
8//! surrounding neighbors of each cell, to a "push" model where we update the neighbors of each
9//! active cell instead.
10//!
11//! A `HashSet` is generally a good choice for very sparse infinite grids, however for this
12//! problem we'll pack all dimensions into a single `vec` to achieve a five times increase
13//! in lookup speed.
14use self::implementation::*;
15use crate::util::grid::*;
16
17/// Use our utility [`Grid`] module to parse the input.
18///
19/// [`Grid`]: crate::util::grid::Grid
20pub fn parse(input: &str) -> Grid<u8> {
21    Grid::parse(input)
22}
23
24/// Part one cells form a cube.
25pub fn part1(input: &Grid<u8>) -> usize {
26    three_dimensions(input)
27}
28
29/// Part two forms a hypercube.
30pub fn part2(input: &Grid<u8>) -> usize {
31    four_dimensions(input)
32}
33
34#[cfg(not(feature = "simd"))]
35mod implementation {
36    use super::*;
37    use crate::util::point::*;
38
39    /// x and y dimensions are in the plane of the input. Each dimension can expand by at most two
40    /// in each axis per round (one positive and one negative). Adding padding at the edges to avoid
41    /// boundary checks gives a maximum width of 8 + 2 × (6 + 1) = 22 for the x and y dimensions and
42    /// 1 + 2 × (6 + 1) = 15 for the z and w dimensions.
43    const X: i32 = 22;
44    const Y: i32 = 22;
45    const Z: i32 = 15;
46    const W: i32 = 15;
47
48    /// Pack a four-dimensional array into a one-dimensional vec to avoid the speed penalty of
49    /// following multiple pointers and increase memory locality for caching.
50    const STRIDE_X: i32 = 1;
51    const STRIDE_Y: i32 = X * STRIDE_X;
52    const STRIDE_Z: i32 = Y * STRIDE_Y;
53    const STRIDE_W: i32 = Z * STRIDE_Z;
54
55    pub(super) fn three_dimensions(input: &Grid<u8>) -> usize {
56        let size = X * Y * Z;
57        let base = STRIDE_X + STRIDE_Y + STRIDE_Z;
58        boot_process(input, size, base, &[0])
59    }
60
61    pub(super) fn four_dimensions(input: &Grid<u8>) -> usize {
62        let size = X * Y * Z * W;
63        let base = STRIDE_X + STRIDE_Y + STRIDE_Z + STRIDE_W;
64        boot_process(input, size, base, &[-1, 0, 1])
65    }
66
67    /// Reuse logic between both parts.
68    fn boot_process(input: &Grid<u8>, size: i32, base: i32, fourth_dimension: &[i32]) -> usize {
69        let dimension = [-1, 0, 1];
70        let mut neighbors = Vec::new();
71
72        // Pre-calculate either the 26 or 80 offsets formed by the combination of dimensions.
73        for x in dimension {
74            for y in dimension {
75                for z in dimension {
76                    for w in fourth_dimension {
77                        let offset = x * STRIDE_X + y * STRIDE_Y + z * STRIDE_Z + w * STRIDE_W;
78                        if offset != 0 {
79                            neighbors.push(offset as isize);
80                        }
81                    }
82                }
83            }
84        }
85
86        let mut active = Vec::with_capacity(5_000);
87        let mut candidates = Vec::with_capacity(5_000);
88
89        // To prevent negative array indices offset the starting cells by seven units in each
90        // dimension. This allows six for growth, plus one for padding to prevent needing edge
91        // checks. Iteration is intentionally column-major, instead of the usual row-major.
92        for x in 0..input.width {
93            for y in 0..input.height {
94                if input[Point::new(x, y)] == b'#' {
95                    let index = 7 * base + x + y * STRIDE_Y;
96                    active.push(index as usize);
97                }
98            }
99        }
100
101        for _ in 0..6 {
102            let mut state = vec![0_u8; size as usize];
103
104            for &cube in &active {
105                for &offset in &neighbors {
106                    // Earlier we converted the offsets from `i32` to signed `isize`. To achieve
107                    // subtraction for negative indices, we use a `wrapping_add_signed` that
108                    // performs [two's complement](https://en.wikipedia.org/wiki/Two%27s_complement) arithmetic.
109                    let index = cube.wrapping_add_signed(offset);
110                    state[index] += 1;
111
112                    if state[index] == 3 {
113                        candidates.push(index);
114                    }
115                }
116            }
117
118            // Active cubes remain active with both two and three neighbors.
119            active.retain(|&cube| state[cube] == 2);
120            // Inactive cubes with exactly three neighbors become active.
121            candidates.retain(|&cube| state[cube] == 3);
122            active.append(&mut candidates);
123        }
124
125        active.len()
126    }
127}
128
129#[cfg(feature = "simd")]
130mod implementation {
131    use std::simd::prelude::*;
132
133    use super::*;
134
135    const LANE_WIDTH: usize = 32;
136    type Vector = Simd<u8, LANE_WIDTH>;
137
138    pub(super) fn three_dimensions(input: &Grid<u8>) -> usize {
139        // Each dimension can expand by at most two in each axis per round. Adding padding at the
140        // edges to avoid boundary checks gives a maximum width of 8 + 2 * (6 + 1) = 22 for the x
141        // and y dimensions and 1 + 2 * (6 + 1) = 15 for the z and w dimensions.
142        let mut current = vec![[[0; 32]; 22]; 15];
143        let mut next = current.clone();
144        // Temporary intermediate state.
145        let mut first = current.clone();
146
147        // Set initial cubes offset from the edges to allow for growth.
148        for point in input.points() {
149            if input[point] == b'#' {
150                current[7][point.y as usize + 7][point.x as usize + 7] = 1;
151            }
152        }
153
154        let zero = Simd::splat(0);
155        let one = Simd::splat(1);
156        let three = Simd::splat(3);
157
158        for round in 0..6 {
159            // Each round state boundary expands by 1 in both positive and negative direction.
160            let edge = 5 - round;
161
162            // Sum xs and ys.
163            for z in (1 + edge)..(14 - edge) {
164                for y in (1 + edge)..(21 - edge) {
165                    let above = xs_sum(&current[z][y - 1]);
166                    let row = xs_sum(&current[z][y]);
167                    let below = xs_sum(&current[z][y + 1]);
168
169                    (row + above + below).copy_to_slice(&mut first[z][y]);
170                }
171            }
172
173            // Sum zs and calculate next state.
174            for z in (1 + edge)..(14 - edge) {
175                for y in (1 + edge)..(21 - edge) {
176                    let above = from_slice(&first[z - 1][y]);
177                    let row = from_slice(&first[z][y]);
178                    let below = from_slice(&first[z + 1][y]);
179                    let state = from_slice(&current[z][y]);
180
181                    let total = row + above + below - state;
182                    let result = (state | total).simd_eq(three).select(one, zero);
183                    result.copy_to_slice(&mut next[z][y]);
184                }
185            }
186
187            (current, next) = (next, current);
188        }
189
190        current.iter().flatten().flatten().map(|&b| usize::from(b)).sum()
191    }
192
193    pub(super) fn four_dimensions(input: &Grid<u8>) -> usize {
194        // Same size logic as part one with added `w` dimension.
195        let mut current = vec![[[[0; 32]; 22]; 15]; 15];
196        let mut next = current.clone();
197        // Temporary intermediate state.
198        let mut first = current.clone();
199        let mut second = current.clone();
200
201        // Set initial cubes offset from the edges to allow for growth.
202        for point in input.points() {
203            if input[point] == b'#' {
204                current[7][7][point.y as usize + 7][point.x as usize + 7] = 1;
205            }
206        }
207
208        let zero = Simd::splat(0);
209        let one = Simd::splat(1);
210        let three = Simd::splat(3);
211
212        for round in 0..6 {
213            // Each round state boundary expands by 1 in both positive and negative direction.
214            let edge = 5 - round;
215
216            // Sum xs and ys.
217            for w in (1 + edge)..(14 - edge) {
218                for z in (1 + edge)..(14 - edge) {
219                    for y in (1 + edge)..(21 - edge) {
220                        let above = xs_sum(&current[w][z][y - 1]);
221                        let row = xs_sum(&current[w][z][y]);
222                        let below = xs_sum(&current[w][z][y + 1]);
223
224                        (row + above + below).copy_to_slice(&mut first[w][z][y]);
225                    }
226                }
227            }
228
229            // Sum zs.
230            for w in (1 + edge)..(14 - edge) {
231                for z in (1 + edge)..(14 - edge) {
232                    for y in (1 + edge)..(21 - edge) {
233                        let above = from_slice(&first[w][z - 1][y]);
234                        let row = from_slice(&first[w][z][y]);
235                        let below = from_slice(&first[w][z + 1][y]);
236
237                        (row + above + below).copy_to_slice(&mut second[w][z][y]);
238                    }
239                }
240            }
241
242            // Sum ws and calculate next state.
243            for w in (1 + edge)..(14 - edge) {
244                for z in (1 + edge)..(14 - edge) {
245                    for y in (1 + edge)..(21 - edge) {
246                        let above = from_slice(&second[w - 1][z][y]);
247                        let row = from_slice(&second[w][z][y]);
248                        let below = from_slice(&second[w + 1][z][y]);
249                        let state = from_slice(&current[w][z][y]);
250
251                        let total = row + above + below - state;
252                        let result = (state | total).simd_eq(three).select(one, zero);
253                        result.copy_to_slice(&mut next[w][z][y]);
254                    }
255                }
256            }
257
258            (current, next) = (next, current);
259        }
260
261        current.iter().flatten().flatten().flatten().map(|&b| usize::from(b)).sum()
262    }
263
264    #[inline]
265    fn from_slice(slice: &[u8]) -> Vector {
266        Simd::from_slice(slice)
267    }
268
269    /// Create SIMD vector of the sum of left, right and center lanes.
270    #[inline]
271    fn xs_sum(slice: &[u8]) -> Vector {
272        let center = Simd::from_slice(slice);
273        let left = center.shift_elements_left::<1>(0);
274        let right = center.shift_elements_right::<1>(0);
275
276        center + left + right
277    }
278}