Skip to main content

aoc/year2021/
day11.rs

1//! # Dumbo Octopus
2//!
3//! This puzzle resembles the [`Day 9`] flood fill a little. Since there are only 100 octopuses
4//! a fixed-size array is used to track current energy levels. Once every octopus has been bumped
5//! at the start of a turn, an energy level of zero means that the octopus has already flashed.
6//! Each time an octopus flashes it bumps its neighbors' energy levels, which can propagate
7//! recursively through the entire grid.
8//!
9//! The 10x10 grid is padded by 1 on either side with zeroes so that we can avoid boundary checks.
10//!
11//! [`Day 9`]: crate::year2021::day09
12use crate::util::parse::*;
13
14type Input = [u8; 144];
15
16pub fn parse(input: &str) -> Input {
17    let mut grid = [0; 144];
18
19    for (y, row) in input.lines().enumerate() {
20        for (x, b) in row.bytes().enumerate() {
21            grid[12 * (y + 1) + (x + 1)] = b.to_decimal();
22        }
23    }
24
25    grid
26}
27
28pub fn part1(input: &Input) -> u64 {
29    let (total, _) = simulate(input, |_, steps| steps < 100);
30    total
31}
32
33pub fn part2(input: &Input) -> u64 {
34    let (_, steps) = simulate(input, |flashes, _| flashes < 100);
35    steps
36}
37
38fn simulate(input: &Input, predicate: fn(u64, u64) -> bool) -> (u64, u64) {
39    let mut grid = *input;
40    let mut todo = Vec::with_capacity(100);
41
42    let mut flashes = 0;
43    let mut steps = 0;
44    let mut total = 0;
45
46    while predicate(flashes, steps) {
47        flashes = 0;
48
49        // Bump each octopus's energy level by one. If it flashes then add to `todo` queue.
50        for y in 0..10 {
51            for x in 0..10 {
52                let index = 12 * (y + 1) + (x + 1);
53                bump_octopus(&mut grid, &mut todo, index);
54            }
55        }
56
57        // Process each flash, possibly adding more to the queue.
58        while let Some(i) = todo.pop() {
59            flashes += 1;
60
61            for next in [i + 1, i + 11, i + 12, i + 13, i - 1, i - 11, i - 12, i - 13] {
62                if grid[next] > 0 {
63                    bump_octopus(&mut grid, &mut todo, next);
64                }
65            }
66        }
67
68        steps += 1;
69        total += flashes;
70    }
71
72    (total, steps)
73}
74
75/// Increments an octopus's energy. If it reaches 10, it flashes and is added to the queue.
76#[inline]
77fn bump_octopus(grid: &mut [u8], todo: &mut Vec<usize>, index: usize) {
78    if grid[index] < 9 {
79        grid[index] += 1;
80    } else {
81        grid[index] = 0;
82        todo.push(index);
83    }
84}