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(c, .) %>%
as.numeric()
}
puzzle_data <- local({
GET(paste0(base_url, "/input"),
session_cookie) %>%
content(encoding = "UTF-8") %>%
parse_puzzle_data()
})
2 Puzzle Day 15
2.1 Part 1
2.1.1 Description
— Day 15: Oxygen System —
Out here in deep space, many things can go wrong. Fortunately, many of those things have indicator lights. Unfortunately, one of those lights is lit: the oxygen system for part of the ship has failed!
According to the readouts, the oxygen system must have failed days ago after a rupture in oxygen tank two; that section of the ship was automatically sealed once oxygen levels went dangerously low. A single remotely-operated repair droid is your only option for fixing the oxygen system.
The Elves’ care package included an Intcode program (your puzzle input) that you can use to remotely control the repair droid. By running that program, you can direct the repair droid to the oxygen system and fix the problem.
The remote control program executes the following steps in a loop forever:
- Accept a movement command via an input instruction.
- Send the movement command to the repair droid.
- Wait for the repair droid to finish the movement operation.
- Report on the status of the repair droid via an output instruction.
Only four movement commands are understood: north (1), south (2), west (3), and east (4). Any other command is invalid. The movements differ in direction, but not in distance: in a long enough east-west hallway, a series of commands like 4,4,4,4,3,3,3,3 would leave the repair droid back where it started.
The repair droid can reply with any of the following status codes:
-
0: The repair droid hit a wall. Its position has not changed. -
1: The repair droid has moved one step in the requested direction. -
2: The repair droid has moved one step in the requested direction; its new position is the location of the oxygen system.
You don’t know anything about the area around the repair droid, but you can figure it out by watching the status codes.
For example, we can draw the area using D for the droid, # for walls, . for locations the droid can traverse, and empty space for unexplored locations. Then, the initial state looks like this:
D
To make the droid go north, send it 1. If it replies with 0, you know that location is a wall and that the droid didn’t move:
#
D
To move east, send 4; a reply of 1 means the movement was successful:
#
.D
Then, perhaps attempts to move north (1), south (2), and east (4) are all met with replies of 0:
##
.D#
#
Now, you know the repair droid is in a dead end. Backtrack with 3 (which you already know will get a reply of 1 because you already know that location is open):
##
D.#
#
Then, perhaps west (3) gets a reply of 0, south (2) gets a reply of 1, south again (2) gets a reply of 0, and then west (3) gets a reply of 2:
##
#..#
D.#
#
Now, because of the reply of 2, you know you’ve found the oxygen system! In this example, it was only 2 moves away from the repair droid’s starting position.
What is the fewest number of movement commands required to move the repair droid from its starting position to the location of the oxygen system?
2.1.2 Solution
We further finetune the code from Day 13 @ 2019 (and get rid of some legacy code). The basic idea is to first build the complete maze BFS (as we need the full maze for part 2 anyways). Then, we run a BFS to find the shortest path form start to end.
print.maze <- function(x, ...) {
margins <- apply(x[, 1:2], 2L, min)
x_norm <- sweep(x[, 1:2], 2, margins, \(x, y) x - y + 1L)
m <- matrix(".", max(x_norm[, 2L]), max(x_norm[, 1L]))
m[x_norm[, 2:1]] <- case_when(
x[, 3L] == -1L ~ "S",
x[, 3L] == 0L ~ "#",
x[, 3L] == 1L ~ " ",
x[, 3L] == 2L ~ "Z"
)
apply(m, 1, paste, collapse = "") %>%
paste(collapse = "\n") %>%
cat()
invisible(x)
}
parse_op_codes_fast <- function(op_codes = puzzle_data, input = numeric(0L),
verbose = FALSE) {
ip <- 1L
rel_base <- 0L
out_buffer <- numeric(0L)
out_len <- 0L
out_block <- integer(1L)
block_size <- 1L # size of memory
maze <- matrix(c(0L, 0L, -1L), 1L, 3L,
dimnames = list(NULL, c("x", "y", "type")))
grow_memory <- function(idx) {
if (idx > length(op_codes)) {
new_size <- ceiling(idx / block_size) * block_size
op_codes <<- c(op_codes, rep(0, new_size - length(op_codes)))
}
}
append_out <- function(val) {
if (out_len + 1L > length(out_buffer)) {
new_size <- length(out_buffer) + out_block
out_buffer <<- c(out_buffer, rep(0, new_size - length(out_buffer)))
}
out_len <<- out_len + 1L
out_buffer[out_len] <<- val
}
get_val <- function(param, mode) {
if (mode == 0L) {
grow_memory(param + 1L)
return(op_codes[param + 1L])
} else if (mode == 1L) {
return(param)
} else if (mode == 2L) {
idx <- rel_base + param + 1L
grow_memory(idx)
return(op_codes[idx])
} else {
stop("unknown mode")
}
}
get_addr <- function(param, mode) {
if (mode == 0L) {
return(param + 1L)
} else if (mode == 2L) {
return(rel_base + param + 1L)
} else {
stop("invalid write mode")
}
}
get_key <- function(...) {
paste(c(...), collapse = ",")
}
pick_dir <- function(pos) {
for (d in seq_along(dirs)) {
dir <- dirs[[d]]
np <- pos + dir
k <- get_key(np)
if (!exists(k, visited)) {
return (d)
}
}
## no unseen possibility at this stage => go back
if (length(stack) > 1L) {
return(stack[[length(stack)]]$back)
}
return (NA_integer_)
}
dirs <- list(c(0L, -1L),
c(0L, 1L),
c(-1L, 0L),
c(1L, 0L))
opp_dir <- c(2L, 1L, 4L, 3L)
visited <- new.env(parent = emptyenv())
pos <- c(0L, 0L)
visited[[get_key(pos)]] <- TRUE
stack <- list(
list(
pos = pos,
back = NA_integer_
)
)
halt <- done <- FALSE
while (!halt) {
instr <- op_codes[ip]
op <- instr %% 100L
modes <- c(
(instr %/% 100L) %% 10L,
(instr %/% 1000L) %% 10L,
(instr %/% 10000L) %% 10L
)
if (op == 1L) { # add
a <- get_val(op_codes[ip + 1L], modes[1L])
b <- get_val(op_codes[ip + 2L], modes[2L])
addr <- get_addr(op_codes[ip + 3L], modes[3L])
grow_memory(addr)
op_codes[addr] <- a + b
ip <- ip + 4L
} else if (op == 2L) { # mul
a <- get_val(op_codes[ip + 1L], modes[1L])
b <- get_val(op_codes[ip + 2L], modes[2L])
addr <- get_addr(op_codes[ip + 3L], modes[3L])
grow_memory(addr)
op_codes[addr] <- a * b
ip <- ip + 4L
} else if (op == 3L) { # input
if (done) {
halt <- TRUE
next
}
dir <- pick_dir(pos)
if (is.na(dir)) {
done <- TRUE
next
}
addr <- get_addr(op_codes[ip + 1L], modes[1L])
grow_memory(addr)
op_codes[addr] <- dir
ip <- ip + 2L
} else if (op == 4L) { # output
val <- get_val(op_codes[ip + 1L], modes[1L])
step <- dirs[[dir]]
prev_pos <- pos
next_pos <- pos + step
k <- get_key(next_pos)
if (!exists(k, visited)) {
maze <- rbind(maze, c(next_pos, val))
}
visited[[k]] <- TRUE
if (val %in% 1:2) {
pos <- next_pos
back_dir <- opp_dir[dir]
if (!is.na(stack[[length(stack)]]$back) &&
dir == stack[[length(stack)]]$back) {
## backtrack
stack <- stack[-length(stack)]
} else {
## new depth save state
stack <- c(stack, list(list(pos = pos, back = back_dir)))
}
}
if (verbose) cat(val, "\n")
ip <- ip + 2L
} else if (op == 5L) { # jump-if-true
a <- get_val(op_codes[ip + 1L], modes[1L])
b <- get_val(op_codes[ip + 2L], modes[2L])
if (a != 0L) {
ip <- b + 1L
} else {
ip <- ip + 3L
}
} else if (op == 6L) { # jump-if-false
a <- get_val(op_codes[ip + 1L], modes[1L])
b <- get_val(op_codes[ip + 2L], modes[2L])
if (a == 0L) {
ip <- b + 1L
} else {
ip <- ip + 3L
}
} else if (op == 7L) { # less than
a <- get_val(op_codes[ip + 1L], modes[1L])
b <- get_val(op_codes[ip + 2L], modes[2L])
addr <- get_addr(op_codes[ip + 3L], modes[3L])
grow_memory(addr)
op_codes[addr] <- as.numeric(a < b)
ip <- ip + 4L
} else if (op == 8L) { # equals
a <- get_val(op_codes[ip + 1L], modes[1L])
b <- get_val(op_codes[ip + 2L], modes[2L])
addr <- get_addr(op_codes[ip + 3L], modes[3L])
grow_memory(addr)
op_codes[addr] <- as.numeric(a == b)
ip <- ip + 4L
} else if (op == 9L) { # adjust relative base
a <- get_val(op_codes[ip + 1L], modes[1L])
rel_base <- rel_base + a
ip <- ip + 2L
} else if (op == 99L) { # halt
halt <- TRUE
} else {
stop("Unknown opcode ", op)
}
}
class(maze) <- "maze"
maze
}
shortest_path <- function(maze) {
start <- maze[maze[, "type"] == -1L, c("x", "y")]
goal <- maze[maze[, "type"] == 2L, c("x", "y")]
free_cells <- maze[maze[, "type"] != 0L, c("x", "y")]
free_keys <- paste(free_cells[, 1L], free_cells[, 2L], sep = ",")
free_set <- new.env(parent = emptyenv())
visited <- new.env(parent = emptyenv())
for (k in free_keys) {
free_set[[k]] <- TRUE
}
get_key <- function(p) {
paste(p, collapse = ",")
}
dirs <- list(
c(0L, -1L),
c(0L, 1L),
c(-1L, 0L),
c(1L, 0L)
)
# BFS-Queue
queue <- list(
list(
pos = start,
path = list()
)
)
visited[[get_key(start)]] <- TRUE
while (length(queue) > 0L) {
current <- queue[[1L]]
queue <- queue[-1L]
if (identical(current$pos, goal)) {
return(unlist(current$path))
}
for (d in seq_along(dirs)) {
np <- current$pos + dirs[[d]]
k <- get_key(np)
if (exists(k, free_set) && !exists(k, visited)) {
visited[[k]] <- TRUE
queue <- c(
queue,
list(list(pos = np,
path = c(current$path, d))
)
)
}
}
}
return(NULL)
}
maze <- parse_op_codes_fast(puzzle_data)
shortest_path(maze) %>%
length()
## [1] 230
2.2 Part 2
2.2.1 Description
— Part Two —
You quickly repair the oxygen system; oxygen gradually fills the area.
Oxygen starts in the location containing the repaired oxygen system. It takes one minute for oxygen to spread to all open locations that are adjacent to a location that already contains oxygen. Diagonal locations are not adjacent.
In the example above, suppose you’ve used the droid to explore the area fully and have the following map (where locations that currently contain oxygen are marked O):
##
#..##
#.#..#
#.O.#
###
Initially, the only location which contains oxygen is the location of the repaired oxygen system. However, after one minute, the oxygen spreads to all open (.) locations that are adjacent to a location containing oxygen:
##
#..##
#.#..#
#OOO#
###
After a total of two minutes, the map looks like this:
##
#..##
#O#O.#
#OOO#
###
After a total of three minutes:
##
#O.##
#O#OO#
#OOO#
###
And finally, the whole region is full of oxygen after a total of four minutes:
##
#OO##
#O#OO#
#OOO#
###
So, in this example, all locations contain oxygen after 4 minutes.
Use the repair droid to get a complete map of the area. How many minutes will it take to fill with oxygen?
2.2.2 Solution
For the second part, we start from the goal and flood the maze with oxygen.
flood <- function(maze) {
get_neighbors <- function(pos) {
dirs <- rbind(
c(-1L, 0L),
c(1L, 0L),
c(0L, -1L),
c(0L, 1L)
)
nbs <- apply(pos, 1L, function(r) t(t(dirs) + r), simplify = FALSE) %>%
do.call(rbind, .)
nbs <- nbs[!duplicated(nbs), , drop = FALSE]
nbs <- nbs[between(nbs[, 1L], 1L, nrow(m)) &
between(nbs[, 2L], 1L, ncol(m)), , drop = FALSE]
if (nrow(nbs) == 0L) {
return(matrix(NA_integer_, 0L, 2L))
}
free <- is.na(m[nbs])
return (nbs[free, , drop = FALSE])
}
margins <- apply(maze[, 1:2], 2L, min)
x_norm <- sweep(maze[, 1:2], 2, margins, \(x, y) x - y + 1L)
m <- matrix("#", max(x_norm[, 2L]), max(x_norm[, 1L]))
m[x_norm[, 2:1]] <- case_when(
maze[, 3L] %in% c(-1L, 1L, 2L) ~ NA_character_,
maze[, 3L] == 0L ~ "#"
)
queue <- x_norm[maze[, 3L] == 2L, 2:1, drop = FALSE]
mins <- -1L
while(nrow(queue) > 0L) {
mins <- mins + 1L
pos <- queue
queue <- get_neighbors(pos)
m[pos] <- "O"
}
mins
}
flood(maze)
## [1] 288