1 Setup
1.1 Libraries
library(httr)
library(xml2)
library(magrittr)
library(dplyr)
library(purrr)
library(stringr)
1.2 Retrieve Data from AoC
session_cookie <- set_cookies(session = keyring::key_get("AoC-GitHub-Cookie"))
base_url <- paste0("https://adventofcode.com/", params$year, "/day/", params$task_nr)
puzzle <- GET(base_url,
session_cookie) %>%
content(encoding = "UTF-8") %>%
xml_find_all("///article") %>%
lapply(as.character)
parse_puzzle_data <- function(text_block = readClipboard()) {
if (length(text_block) == 1L) {
text_block <- text_block %>%
str_split("\n") %>%
extract2(1L) %>%
keep(nzchar)
}
text_block %>%
str_split("") %>%
do.call(rbind, .) %>%
set_class("light_array")
}
puzzle_data <- local({
GET(paste0(base_url, "/input"),
session_cookie) %>%
content(encoding = "UTF-8") %>%
parse_puzzle_data()
})
2 Puzzle Day 18
2.1 Part 1
2.1.1 Description
— Day 18: Like a GIF For Your Yard —
After the million lights incident, the fire code has gotten stricter: now, at most ten thousand lights are allowed. You arrange them in a 100x100 grid.
Never one to let you down, Santa again mails you instructions on the ideal lighting configuration. With so few lights, he says, you’ll have to resort to animation.
Start by setting your lights to the included initial configuration (your puzzle input). A #
means “on”, and a .
means “off”.
Then, animate your grid in steps, where each step decides the next configuration based on the current one. Each light’s next state (either on or off) depends on its current state and the current states of the eight lights adjacent to it (including diagonals). Lights on the edge of the grid might have fewer than eight neighbors; the missing ones always count as “off”.
For example, in a simplified 6x6 grid, the light marked A
has the neighbors numbered 1
through 8
, and the light marked B
, which is on an edge, only has the neighbors marked 1
through 5
:
1B5...
234...
......
..123.
..8A4.
..765.
The state a light should have next is based on its current state (on or off) plus the number of neighbors that are on:
-
A light which is on stays on when
2
or3
neighbors are on, and turns off otherwise. -
A light which is off turns on if exactly
3
neighbors are on, and stays off otherwise.
All of the lights update simultaneously; they all consider the same current state before moving to the next.
Here’s a few steps from an example configuration of another 6x6 grid:
Initial state:
.#.#.#
...##.
#....#
..#...
#.#..#
####..
After 1 step:
..##..
..##.#
...##.
......
#.....
#.##..
After 2 steps:
..###.
......
..###.
......
.#....
.#....
After 3 steps:
...#..
......
...#..
..##..
......
......
After 4 steps:
......
......
..##..
..##..
......
......
After 4
steps, this example has four lights on.
In your grid of 100x100 lights, given your initial configuration, how many lights are on after 100 steps?
2.1.2 Solution
The solution is rather straight forward. However, since R is rather slow (while featuring very nice matrix indexing options), we re-implemented the solution in C++, which gave us a huge speed gain. The original code can be found in the appendix.
#ifndef STANDALONE
#include <Rcpp.h>
using namespace Rcpp;
#else
#include <iostream>
#endif
#include <string>
#include <vector>
int count_lights(const std::vector<std::vector<char>>& light_array,
int iterations,
bool consider_corners = true) {
int n = light_array.size();
int m = light_array[0].size();
std::vector<std::vector<char>> state = light_array;
std::vector<std::vector<char>> new_state = state;
for (int k = 1; k <= iterations; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int cnt_on = 0;
bool is_corner = (i == 0 && j == 0) || (i == 0 && j == m - 1) || (i == n - 1 && j == 0) ||
(i == n - 1 && j == m - 1);
if (consider_corners || !is_corner) {
for (int offset_i = -1; offset_i <= 1; offset_i++) {
for (int offset_j = -1; offset_j <= 1; offset_j++) {
int ni = i + offset_i;
int nj = j + offset_j;
if (ni >= 0 && ni < n && nj >= 0 && nj < m && !(offset_i == 0 && offset_j == 0)) {
if (state[ni][nj] == '#') {
cnt_on++;
}
}
}
}
if ((state[i][j] == '#' && (cnt_on == 2 || cnt_on == 3)) ||
(state[i][j] == '.' && cnt_on == 3)) {
new_state[i][j] = '#';
} else {
new_state[i][j] = '.';
}
}
}
}
state = new_state;
}
int cnt_on = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (state[i][j] == '#') {
cnt_on++;
}
}
}
return cnt_on;
}
#ifndef STANDALONE
// [[Rcpp::export]]
int count_lights(CharacterMatrix light_array, int iterations, bool consider_corners = true) {
int n = light_array.rows();
int m = light_array.cols();
std::vector<std::vector<char>> stl_array(n, std::vector<char>(m));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
stl_array[i][j] = Rcpp::as<std::string>(light_array(i, j))[0];
}
}
return count_lights(stl_array, iterations, consider_corners);
}
#else
int main() {
std::vector<std::vector<char>> light_array = {{'.', '#', '.', '#', '.', '#'},
{'.', '.', '.', '#', '#', '.'},
{'#', '.', '.', '.', '.', '#'},
{'.', '.', '#', '.', '.', '.'},
{'#', '.', '#', '.', '.', '#'},
{'#', '#', '#', '#', '.', '.'}};
int iterations = 4;
bool consider_corners = true;
int result = count_lights(light_array, iterations, consider_corners);
std::cout << "Number of lights on after " << iterations << " iterations: " << result << std::endl;
return 0;
}
#endif
count_lights(puzzle_data, 100L)
## [1] 768
2.2 Part 2
2.2.1 Description
— Part Two —
You flip the instructions over; Santa goes on to point out that this is all just an implementation of Conway’s Game of Life. At least, it was, until you notice that something’s wrong with the grid of lights you bought: four lights, one in each corner, are stuck on and can’t be turned off. The example above will actually run like this:
Initial state:
##.#.#
...##.
#....#
..#...
#.#..#
####.#
After 1 step:
#.##.#
####.#
...##.
......
#...#.
#.####
After 2 steps:
#..#.#
#....#
.#.##.
...##.
.#..##
##.###
After 3 steps:
#...##
####.#
..##.#
......
##....
####.#
After 4 steps:
#.####
#....#
...#..
.##...
#.....
#.#..#
After 5 steps:
##.###
.##..#
.##...
.##...
#.#...
##...#
After 5
steps, this example now has 17
lights on.
In your grid of 100x100 lights, given your initial configuration, but with the four corners always in the on state, how many lights are on after 100 steps?
2.2.2 Solution
We just need to leave out the corners in our calculation and off we go.
count_lights(puzzle_data, 100L, FALSE)
## [1] 781
3 R Legacy Solution
print.light_array <- function(x, ..., raw = FALSE) {
if (raw) {
NextMethod(x)
} else {
apply(x, 1, paste, collapse = "") %>%
paste(collapse = "\n") %>%
cat()
}
}
get_neighbors <- function(dims) {
rows <- 1:dims[1L]
cols <- 1:dims[2L]
idx <- expand.grid(row = rows, col = cols) %>%
as.matrix()
nbs <- lapply(seq_len(nrow(idx)), function(i) {
node <- c(idx[i, ])
dirs <- -1:1
nbs <- expand.grid(row = dirs, col = dirs)
nbs <- nbs[!(nbs[, "row"] == 0L & nbs[, "col"] == 0L), ]
nbs <- t(t(nbs) + node)
cbind(row_orig = node[1L],
col_orig = node[2L],
nbs[between(nbs[, "row"], 1L, dims[1L]) &
between(nbs[, "col"], 1L, dims[2L]), ]
)
})
do.call(rbind, nbs) %>%
as_tibble() %>%
group_by(row_orig, col_orig) %>%
summarize(nbs = list(cbind(row, col)),
.groups = "rowwise") %>%
rename(row = row_orig, col = col_orig) %>%
mutate(is_corner = (row == 1L & col == 1L) |
(row == 1L & col == dims[2L]) |
(row == dims[1L] & col == 1L) |
(row == dims[1L] & col == dims[2L]))
}
get_new_status <- function(row, col, nbs, light_array) {
nb_status <- sum(light_array[nbs] == "#")
if (light_array[row, col] == "#") {
new_status <- if_else(between(nb_status, 2L, 3L), "#", ".")
} else {
new_status <- if_else(nb_status == 3L, "#", ".")
}
new_status
}
switch_lights <- function(light_array, iterations, consider_corners = TRUE) {
dd <- dim(light_array)
nbs <- get_neighbors(dd)
for (i in 1:iterations) {
cat("Iteration ", i, "\n")
new_lights <- nbs %>%
mutate(status = get_new_status(row, col, nbs, light_array),
status = case_when(
consider_corners | !is_corner ~ status,
TRUE ~ "#"
)
) %>%
pull(status)
light_array[] <- new_lights
}
light_array
}
count_lights <- function(light_array, iterations, consider_corners = TRUE) {
final_state <- switch_lights(light_array, iterations, consider_corners)
sum(final_state == "#")
}
count_lights(puzzle_data, 100L)
count_lights(puzzle_data, 100L, FALSE)