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: isize = 24;
13const NEIGHBORS: [isize; 6] = [-1, 1, -SIZE, SIZE, -SIZE * SIZE, SIZE * SIZE];
14
15pub fn parse(input: &str) -> Vec<u8> {
16 let size = SIZE as usize;
17 let mut cube = vec![0; size * size * size];
18 // Leave a 1 layer boundary around the outside for the part two flood fill
19 // and also so that we don't have to use boundary checks when checking neighbors.
20 input.iter_unsigned().chunk::<3>().for_each(|[x, y, z]: [usize; 3]| {
21 cube[(x + 1) * size * size + (y + 1) * size + (z + 1)] = 1;
22 });
23 cube
24}
25
26pub fn part1(input: &[u8]) -> u32 {
27 // The exposed surface area is the 6 faces of the cubes minus any neighbors.
28 count(input, |x| 6 - x)
29}
30
31pub fn part2(input: &[u8]) -> u32 {
32 // "Paint" the outside of the cube with water drops.
33 // Use 8 as the nearest power of two greater than 6.
34 let mut cube = input.to_vec();
35 cube[0] = 8;
36
37 let mut todo = vec![0_usize];
38
39 while let Some(index) = todo.pop() {
40 // We may wrap around but that index will be out of bounds.
41 for next in NEIGHBORS.map(|n| index.wrapping_add_signed(n)) {
42 if next < cube.len() && cube[next] == 0 {
43 cube[next] = 8;
44 todo.push(next);
45 }
46 }
47 }
48
49 // Divide by 8 so that we only count water cubes.
50 count(&cube, |x| x >> 3)
51}
52
53fn count(cube: &[u8], adjust: fn(u32) -> u32) -> u32 {
54 cube.iter()
55 .enumerate()
56 .filter(|&(_, &cell)| cell == 1)
57 .map(|(index, _)| {
58 // No need for boundary checks as all cubes are at least 1 away from the edge.
59 adjust(NEIGHBORS.iter().map(|&n| cube[index.wrapping_add_signed(n)] as u32).sum())
60 })
61 .sum()
62}