1 Setup
1.1 Libraries
library(httr)
library(xml2)
library(magrittr)
library(dplyr)
library(purrr)
library(stringr)
library(knitr)
library(cli)
1.2 Retrieve Data from AoC
session_cookie <- set_cookies(session = keyring::key_get("AoC-GitHub-Cookie"))
base_url <- paste0("https://adventofcode.com/2024/day/", params$task_nr)
puzzle <- GET(base_url,
session_cookie) %>%
content(encoding = "UTF-8") %>%
xml_find_all("///article") %>%
lapply(as.character)
puzzle_data <- local({
GET(paste0(base_url, "/input"),
session_cookie) %>%
content(encoding = "UTF-8") %>%
str_split("\n") %>%
extract2(1L) %>%
str_split("") %>%
do.call(rbind, .)
})
2 Puzzle Day 6
2.1 Part 1
2.1.1 Description
— Day 6: Guard Gallivant —
The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab… in the year 1518! It turns out that having direct access to history is very convenient for a group of historians.
You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab.
Maybe you can work out where the guard will go ahead of time so that The Historians can search safely?
You start by making a map (your puzzle input) of the situation. For example:
....#.....
.........#
..........
..#.......
.......#..
..........
.#..^.....
........#.
#.........
......#...
The map shows the current position of the guard with ^
(to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #
.
Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps:
- If there is something directly in front of you, turn right 90 degrees.
- Otherwise, take a step forward.
Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes):
....#.....
....^....#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#...
Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction:
....#.....
........>#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#...
Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward:
....#.....
.........#
..........
..#.......
.......#..
..........
.#......v.
........#.
#.........
......#...
This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent):
....#.....
.........#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#v..
By predicting the guard’s route, you can determine which specific positions in the lab will be in the patrol path. Including the guard’s starting position, the positions visited by the guard before leaving the area are marked with an X
:
....#.....
....XXXXX#
....X...X.
..#.X...X.
..XXXXX#X.
..X.X.X.X.
.#XXXXXXX.
.XXXXXXX#.
#XXXXXXX..
......#X..
In this example, the guard will visit 41
distinct positions on your map.
Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area?
2.1.2 Solution
We solve this puzzle by simulating the alk field by field. An earlier version of this code used more sophisticated indexing, but was for some reasons not clear to me, slower.
Anyways, the algorithm is rather straight forward:
- If we are not seeing a
#
move one field in the current direction and store the step number and current direction in the path (this is done to recognize loops.) - If we hit a
#
first step back (reducing the step counter to undo the step) and then turn. - Continue until we would be outside the grid.
N.B. Most of the data stored (step_number
or direction
) is not needed for the first
puzzle, where we simply want to get the number of fields visited. Also the part where we
can resume an earlier path. However, we will need (and explain) these parts in the section
of puzzle 2.
get_field_id <- function(idx) {
paste(idx, collapse = "/")
}
walk_maze <- function(maze, trodden_path = NULL) {
pos <- which(maze == "^", arr.ind = TRUE)
continue <- loop <- done <- FALSE
dir <- "up"
walk <- function(pos, dir, backward = FALSE) {
offset <- switch(
dir,
up = cbind(-1L, 0L),
right = cbind(0L, 1L),
down = cbind(1L, 0L),
left = cbind(0L, -1L)
)
pos + (1L - 2L * backward) * offset
}
path <- vector("list", prod(dim(maze)))
i <- 1L
step_counter <- 1L
if (!is.null(trodden_path)) {
idx <- seq_along(trodden_path)
path[idx] <- trodden_path
names(path)[idx] <- names(trodden_path)
last_field_idx <- map_dbl(
trodden_path,
max
) %>%
which.max()
last_field <- trodden_path[last_field_idx]
step_counter <- max(last_field[[1L]])
pos <- last_field %>%
names() %>%
str_split(fixed("/")) %>%
extract2(1L) %>%
as.integer() %>%
matrix(ncol = 2L)
dir <- last_field[[1L]] %>%
tail(1L) %>%
names()
i <- length(trodden_path) + 1L
continue <- TRUE
}
while (!done) {
cur_field <- maze[pos]
if (cur_field == "#") {
pos <- walk(pos, dir, TRUE)
dir <- switch(
dir,
up = "right",
right = "down",
down = "left",
left = "up"
)
step_counter <- step_counter - 1L
} else {
id <- get_field_id(pos)
new_step <- step_counter %>%
setNames(dir)
if (id %in% names(path)) {
if (continue) {
## if we continue a path the first step is already recorded so skip
continue <- FALSE
} else {
if (dir %in% names(path[[id]])) {
## loop condition
done <- loop <- TRUE
}
path[[id]] <- c(path[[id]], new_step)
}
} else {
path[[i]] <- new_step
names(path)[[i]] <- id
i <- i + 1L
}
pos <- walk(pos, dir)
step_counter <- step_counter + 1L
}
done <- done || pos[1L] %in% c(0L, nrow(maze) + 1L) ||
pos[2L] %in% c(0L, ncol(maze) + 1L)
}
res <- discard(path, is.null)
attr(res, "loop") <- loop
res
}
path <- walk_maze(puzzle_data)
length(path)
## [1] 4656
2.2 Part 2
2.2.1 Description
— Part Two —
While The Historians begin working around the guard’s patrol route, you borrow their fancy device and step outside the lab. From the safety of a supply closet, you time travel through the last few months and record the nightly status of the lab’s guard post on the walls of the closet.
Returning after what seems like only a few seconds to The Historians, they explain that the guard’s patrol area is simply too large for them to safely search the lab without getting caught.
Fortunately, they are pretty sure that adding a single new obstruction won’t cause a time paradox. They’d like to place the new obstruction in such a way that the guard will get stuck in a loop, making the rest of the lab safe to search.
To have the lowest chance of creating a time paradox, The Historians would like to know all of the possible positions for such an obstruction. The new obstruction can’t be placed at the guard’s starting position - the guard is there right now and would notice.
In the above example, there are only 6
different positions where a new obstruction would cause the guard to get stuck in a loop. The diagrams of these six situations use O
to mark the new obstruction, |
to show a position where the guard moves up/down, -
to show a position where the guard moves left/right, and +
to show a position where the guard moves both up/down and left/right.
Option one, put a printing press next to the guard’s starting position:
....#.....
....+---+#
....|...|.
..#.|...|.
....|..#|.
....|...|.
.#.O^---+.
........#.
#.........
......#...
Option two, put a stack of failed suit prototypes in the bottom right quadrant of the mapped area:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
......O.#.
#.........
......#...
Option three, put a crate of chimney-squeeze prototype fabric next to the standing desk in the bottom right quadrant:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
.+----+O#.
#+----+...
......#...
Option four, put an alchemical retroencabulator near the bottom left corner:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
..|...|.#.
#O+---+...
......#...
Option five, put the alchemical retroencabulator a bit to the right instead:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
....|.|.#.
#..O+-+...
......#...
Option six, put a tank of sovereign glue right next to the tank of universal solvent:
....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
.+----++#.
#+----++..
......#O..
It doesn’t really matter what you choose to use as an obstacle so long as you and The Historians can put it into position without the guard noticing. The important thing is having enough options that you can find one that minimizes time paradoxes, and in this example, there are 6
different positions you could choose.
You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction?
2.2.2 Solution
Any obstacle creating a loop must be placed on the original path. An obstacle placed
somewhere else would simply be never hit. We loop through each field on the path, place
an obstacle there and re-simulate the walk. To detect whether we ended up in a loop, all
we have to check whether the field we are entering was entered already before in the same
direction. To safe some time, we do not regenerate the walk from the beginning at each
iteration but reuse the original path up to the field on which we are placing the new
obstacle. For this reason, we stored the step_counter
in the first place, because to
trim a path, we simply discard and step larger than a given step number.
trim_path <- function(path, idx) {
if (idx > 0L) {
keep(path, ~ any(.x <= idx)) %>%
map(~ .x[.x <= idx])
} else {
NULL
}
}
find_loops <- function(maze, path) {
start_pos <- which(maze == "^", arr.ind = TRUE)
path_fields_nm <- names(path) %>%
setdiff(get_field_id(start_pos))
path_fields <- path_fields_nm %>%
str_split(fixed("/")) %>%
map(~ as.integer(.x) %>% matrix(ncol = 2))
if (interactive()) {
pb <- list(
name = "Checking Candidates",
type = "iterator",
## need to convert to double beforehand otherwise we get an error
total = as.numeric(length(path_fields))
)
} else {
pb <- FALSE
}
idx <- map_lgl(
seq_along(path_fields),
function(i) {
## use global maze to avoid copying large objects in each iteration
cand <- path_fields[[i]]
maze[cand] <- "#"
current_path <- trim_path(path, i - 1L)
new_path <- walk_maze(maze, current_path)
## need to reset the maze
maze[cand] <- "."
attr(new_path, "loop")
},
.progress = pb
)
path_fields_nm[idx]
}
res <- find_loops(puzzle_data, path)
length(res)
## [1] 1575