library(tidyverse)
Day 11
Advent of Code: Worked Solutions
Setup
Import libraries:
Read input from plain-text file into a matrix:
<- read_fwf(
input file = "../input/day11.txt",
col_positions = fwf_widths(rep(1, 10)),
col_types = "i",
show_col_types = FALSE
|>
) as.matrix() |>
unname()
<- ncol(input)
width <- nrow(input) height
Part 1
Define a function to compute the energy boost from a single flash:
<- \(x) lag(x, default = 0)
n <- \(x) lead(x, default = 0)
s <- \(x) t(lag(t(x), default = 0))
w <- \(x) t(lead(t(x), default = 0))
e
<- function(x) {
add_energy n(x) + s(x) + e(x) + w(x) + n(w(x)) + n(e(x)) + s(w(x)) + s(e(x))
}
Define a function to run a single step, which may consist of many flashes until a stable state is reached:
<- function(mtx) {
step
# Initialize
<- mtx + 1
mtx <- matrix(FALSE, nrow = height, ncol = width)
has_flashed
# Repeat until done flashing
repeat {
<- mtx > 9 & !has_flashed
cur_flash
if (all(cur_flash == FALSE)) break
<- has_flashed | cur_flash
has_flashed <- mtx + add_energy(cur_flash)
mtx
}
# Replace all flashed values with 0
replace(mtx, has_flashed, 0)
}
Define a function to count the total individual flashes that occur over a defined number of steps:
<- function(mtx, n_steps) {
count_flashes
<- 0
flashes for (i in 1:n_steps) {
<- step(mtx)
mtx <- flashes + sum(mtx == 0)
flashes
}
flashes }
Run on puzzle input. Count the flashes over 100 steps:
count_flashes(input, 100)
Part 2
Define a function to find the first step when all cells flash in unison:
<- function(mtx) {
first_in_unison <- 0
i
while (any(mtx != 0)) {
<- step(mtx)
mtx <- i + 1
i
}
i }
Run on input:
first_in_unison(input)