aoc/year2022/
day18.rs

1//! # Boiling Boulders
2//!
3//! The lava droplet is a fixed size so we can use a one-dimensional fixed-size array to store the
4//! cube data for speed.
5//!
6//! For part two we use the [flood fill](https://en.wikipedia.org/wiki/Flood_fill) algorithm
7//! starting from any corner to fill the outside space with water. We then use the same exposed
8//! edge counting approach as part one, but only considering faces that touch a water drop.
9use crate::util::iter::*;
10use crate::util::parse::*;
11
12const SIZE: usize = 24;
13
14pub fn parse(input: &str) -> Vec<u8> {
15    let mut cube = vec![0; SIZE * SIZE * SIZE];
16    // Leave a 1 layer boundary around the outside for the part two flood fill
17    // and also so that we don't have to use boundary checks when checking neighbors.
18    input.iter_unsigned().chunk::<3>().for_each(|[x, y, z]: [usize; 3]| {
19        cube[(x + 1) * SIZE * SIZE + (y + 1) * SIZE + (z + 1)] = 1;
20    });
21    cube
22}
23
24pub fn part1(input: &[u8]) -> u32 {
25    // The exposed surface area is the 6 faces of the cubes minus any neighbors.
26    count(input, |x| 6 - x)
27}
28
29pub fn part2(input: &[u8]) -> u32 {
30    // "Paint" the outside of the cube with water drops.
31    // Use 8 as the nearest power of two greater than 6.
32    let mut cube = input.to_vec();
33    cube[0] = 8;
34
35    let mut todo = vec![0_usize];
36
37    while let Some(index) = todo.pop() {
38        // We may wrap around but that index will be out of bounds.
39        for next in [
40            index.wrapping_sub(1),
41            index + 1,
42            index.wrapping_sub(SIZE),
43            index + SIZE,
44            index.wrapping_sub(SIZE * SIZE),
45            index + SIZE * SIZE,
46        ] {
47            if next < cube.len() && cube[next] == 0 {
48                cube[next] = 8;
49                todo.push(next);
50            }
51        }
52    }
53
54    // Divide by 8 so that we only count water cubes.
55    count(&cube, |x| x >> 3)
56}
57
58fn count(cube: &[u8], adjust: fn(u32) -> u32) -> u32 {
59    let mut total = 0;
60
61    for (i, &cell) in cube.iter().enumerate() {
62        if cell == 1 {
63            // No need for boundary checks as all cubes are at least 1 away from the edge.
64            let neighbors = cube[i - 1] as u32
65                + cube[i + 1] as u32
66                + cube[i - SIZE] as u32
67                + cube[i + SIZE] as u32
68                + cube[i - SIZE * SIZE] as u32
69                + cube[i + SIZE * SIZE] as u32;
70            total += adjust(neighbors);
71        }
72    }
73
74    total
75}