Skip to main content

aoc/year2015/
day18.rs

1//! # Like a GIF For Your Yard
2//!
3//! To solve this efficiently we use a [SWAR](https://en.wikipedia.org/wiki/SWAR) approach,
4//! packing 50 lights into a `u64` taking 1 bit each, drawing inspiration from a solution from
5//! [u/terje_wiig_mathisen/](https://github.com/TerjeWiigMathisen/aoc-2015-day18).
6//!
7//! But rather than taking the bits consecutively,
8//! split the odd columns into one int and the even into another - that way, when it is time to
9//! check neighbors, all left and right neighbors of the odd lanes are already available with just
10//! one shift of all the even lanes, and vice versa. We calculate the next generation using no
11//! conditional statements with the following steps.
12//!
13//! 1. Pack the input bytes into register values that can be represented as binary digits, split
14//!    into odd and even lanes. An extra empty row at the bottom reduces later special-casing.
15//!
16//! ```none
17//!                .even .odd
18//!         column: 024   135
19//! #...#.          101   000
20//! .#.##. =>       001   110
21//! ###.#.          111   100
22//! ```
23//!
24//! 2. Perform half-adder and full-adder computation of each bit with its vertical neighbors, using
25//!    only bitwise logic. Just two bit-wise additions provide data for three 2-bit column sums,
26//!    since the left and right neighbors are one bit apart in the opposite parity integer and
27//!    already added in parallel. Visually, for cell e, we are computing a+b+c, d+f, and g+h+i of
28//!    its neighbors.
29//!
30//! ```none
31//!               .odd   .even
32//! ..adg..       ..d..  ..ag..
33//! ..beh..  =>   ..e..  ..bh..
34//! ..cfi..       ..f..  ..ci..
35//!             l,m=d+f  j,k=a+b+c  n,o=g+h+i
36//! ```
37//!
38//! 3. Taking the 3 two-bit column sums learned in the last step, perform two more full-adders to
39//!    form four new bits p, q, r, s, which we could add into a usual four-bit number, but which are
40//!    good enough for our needs as-is. Bit s is set if there are an odd number of neighbors, bit p
41//!    must be clear or we already know there are more than 3 neighbors, and exactly one of bits q
42//!    and r must be set for the final 4-bit sum to have the second bit set.
43//!
44//! ```none
45//!   a d g
46//!   b - h
47//! + c f i
48//! -------
49//!     j k
50//!     l m
51//! +   n o
52//! -------
53//!   p q -
54//!     r s
55//! ```
56//!
57//! 4. Apply the rules using only bitwise logic.
58//!
59//! Consider the binary representation of a 4 bit hex digit.
60//! * A cell stays on if it has 2 or 3 neighbors, binary `0010` or binary `0011`.
61//! * A cell turns on if it has exactly 3 neighbors, binary `0011`.
62//!
63//! If we `OR` the neighbor count with the current cell, either `0000` or `0001` then the
64//! binary representation of a lit cell will always be `0011`.
65//!
66//! Using the bits as labelled above, the next cell is `(e|s) & (q^r) & !p`, masked back
67//! to the 50 bits per integer.
68const MASK: u64 = (1 << 50) - 1;
69const LEFT_CORNER: u64 = 1 << 49;
70const RIGHT_CORNER: u64 = 1 << 0;
71
72/// 100 lights of a single row, split by column parity.
73#[derive(Clone, Copy, Default)]
74pub struct Row {
75    even: u64,
76    odd: u64,
77}
78
79/// Pack the lights into 1 bit each in [big-endian order](https://en.wikipedia.org/wiki/Endianness).
80pub fn parse(input: &str) -> Vec<Row> {
81    let pack = |acc, b| (acc << 1) | u64::from(b & 1);
82    let row = |line: &str| Row {
83        even: line.bytes().step_by(2).fold(0, pack),
84        odd: line.bytes().skip(1).step_by(2).fold(0, pack),
85    };
86
87    input.lines().map(row).chain([Row::default()]).collect()
88}
89
90pub fn part1(input: &[Row]) -> u32 {
91    game_of_life(input, false)
92}
93
94pub fn part2(input: &[Row]) -> u32 {
95    game_of_life(input, true)
96}
97
98fn game_of_life(input: &[Row], part_two: bool) -> u32 {
99    let mut grid = input.to_vec();
100
101    // Corner lights are also stuck on in the initial state.
102    if part_two {
103        grid[0].even |= LEFT_CORNER;
104        grid[0].odd |= RIGHT_CORNER;
105        grid[99].even |= LEFT_CORNER;
106        grid[99].odd |= RIGHT_CORNER;
107    }
108
109    for _ in 0..100 {
110        let mut above;
111        let mut row = Row::default();
112        let mut below = grid[0];
113
114        for y in 0..100 {
115            // Advance row.
116            (above, row, below) = (row, below, grid[y + 1]);
117
118            // Even columns.
119            let (j, k) = full_adder(above.odd, row.odd, below.odd);
120            let (l, m) = half_adder(above.even, below.even);
121            let (n, o) = (j >> 1, k >> 1);
122
123            let (p, q) = full_adder(j, l, n);
124            let (r, s) = full_adder(k, m, o);
125            grid[y].even = (grid[y].even | s) & (q ^ r) & !p & MASK;
126
127            // Odd columns.
128            let (j, k) = full_adder(above.even, row.even, below.even);
129            let (l, m) = half_adder(above.odd, below.odd);
130            let (n, o) = (j << 1, k << 1);
131
132            let (p, q) = full_adder(j, l, n);
133            let (r, s) = full_adder(k, m, o);
134            grid[y].odd = (grid[y].odd | s) & (q ^ r) & !p & MASK;
135        }
136
137        // Set corner lights to always on.
138        if part_two {
139            grid[0].even |= LEFT_CORNER;
140            grid[0].odd |= RIGHT_CORNER;
141            grid[99].even |= LEFT_CORNER;
142            grid[99].odd |= RIGHT_CORNER;
143        }
144    }
145
146    grid.iter().map(|row| row.even.count_ones() + row.odd.count_ones()).sum()
147}
148
149#[inline]
150fn half_adder(a: u64, b: u64) -> (u64, u64) {
151    (a & b, a ^ b)
152}
153
154#[inline]
155fn full_adder(a: u64, b: u64, c: u64) -> (u64, u64) {
156    (a & b | c & (a ^ b), a ^ b ^ c)
157}