1 Setup
1.1 Libraries
library(httr)
library(xml2)
library(tibble)
library(magrittr)
library(dplyr)
library(purrr)
library(stringr)
library(stringi)
library(knitr)
library(cli)
library(bit64)
library(igraph)
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)
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("")
}
puzzle_data <- local({
GET(paste0(base_url, "/input"),
session_cookie) %>%
content(encoding = "UTF-8") %>%
parse_puzzle_data()
})
2 Puzzle Day 21
2.1 Part 1
2.1.1 Description
— Day 21: Keypad Conundrum —
As you teleport onto Santa’s Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship’s computer reveals that when the missing Historian teleported, he arrived in another part of the ship.
The door to that area is locked, but the computer can’t open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door.
The numeric keypad has four rows of buttons: 789
, 456
, 123
, and finally an empty gap followed by 0A
. Visually, they are arranged like this:
+---+---+---+
| 7 | 8 | 9 |
+---+---+---+
| 4 | 5 | 6 |
+---+---+---+
| 1 | 2 | 3 |
+---+---+---+
| 0 | A |
+---+---+
Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead.
The robot has no problem navigating the ship and finding the numeric keypad, but it’s not designed for button pushing: it can’t be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad.
The directional keypad has two rows of buttons: a gap / ^
(up) / A
(activate) on the first row and <
(left) / v
(down) / >
(right) on the second row. Visually, they are arranged like this:
+---+---+
| ^ | A |
+---+---+---+
| < | v | > |
+---+---+---+
When the robot arrives at the numeric keypad, its robotic arm is pointed at the A
button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A
button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm.
For example, to make the robot type 029A
on the numeric keypad, one sequence of inputs on the directional keypad you could use is:
-
<
to move the arm fromA
(its initial position) to0
. -
A
to push the0
button. -
^A
to move the arm to the2
button and push it. -
>^^A
to move the arm to the9
button and push it. -
vvvA
to move the arm to theA
button and push it.
In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A
: <AA>^AvvvA
, <AA>^AvvvA
, and <AA^>AvvvA
.
Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead.
When the robot arrives at the directional keypad, its robot arm is pointed at the A
button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad).
There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A
on the door. One such sequence is v<<A>>A<A>AvA<AA>A<vAAA>^A
.
Unfortunately, the area containing this second directional keypad remote control is currently -40
degrees! Another robot will need to be sent to type on that directional keypad, too.
There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A
on the door. One such sequence is <vA<AA>>AvAA<A>A<v<A>>AvAA<vA>A<v<A>A>AAvAA<v<A>A>AAAvA<^A>A
.
Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself.
Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots’ directional keypads, and the numeric keypad:
<vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A
v<<A>>^A<A>AvA<^AA>A<vAAA>^A
<A^A>^^AvvvA
029A
In summary, there are the following keypads:
- One directional keypad that you are using.
- Two directional keypads that robots are using.
- One numeric keypad (on a door) that a robot is using.
It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don’t do that. All robots will initially aim at the keypad’s A
key, wherever it is.
To unlock the door, five codes will need to be typed on its numeric keypad. For example:
029A
980A
179A
456A
379A
For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad:
029A: <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A
980A: <v<A>>^AAAvA^A<vA<AA>>^AvAA<^A>A<v<A>A>^AAAvA<^A>A<vA>^A<A>A
179A: <v<A>>^A<vA<A>>^AAvAA<^A>A<v<A>>^AAvA^A<vA>^AA<A>A<v<A>A>^AAAvA<^A>A
456A: <v<A>>^AA<vA<A>>^AAvAA<^A>A<vA>^A<A>A<vA>^A<A>A<v<A>A>^AAvA<^A>A
379A: <v<A>>^AvA^A<vA<AA>>^AAvA<^A>AAvA^A<vA>^AA<A>A<v<A>A>^AAAvA<^A>A
The Historians are getting nervous; the ship computer doesn’t remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You’ll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary.
The complexity of a single code (like 029A
) is equal to the result of multiplying these two values:
-
The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for
029A
, this would be68
. -
The numeric part of the code (ignoring leading zeroes); for
029A
, this would be29
.
In the above example, complexity of the five codes can be found by calculating 68 * 29
, 60 * 980
, 68 * 179
, 64 * 456
, and 64 * 379
. Adding these together produces 126384
.
Find the fewest number of button presses you’ll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?
2.1.2 Solution
This puzzle took my way longer than it should have. Anyways, the idea is as follows:
- Create graphs for both pads to facilitate calculating shorted paths between keys.
- To significantly reduce the amount of paths between 2 keys we use several heuristics:
- As we always start at
A
we see that<
is the most expensive key to reach, followed byv
. ^
and<
have teh same costs, however, the former requires a<
on the next robot, making it slightly more expansive. Thus the cheapest keys to reach are>
,^
,v
and<
(in this order).- Consecutives moves in the same directiona re cheaper than alternating on the next
layer.
>>^
and>^>
will end up on the same key, but the next robot needs more moves to type the latter sequence:vAA^<A
vsvA^<A>vA
.
- As we always start at
- We end up with a list of shortest moves. For some key combinations there are still 2
options, for instance we can move from
A -> v
wither byv|<
or via<|v
. - We maintain a list of all moves from each key to all the other keys. If an entry has only a single entry it means that there is just one optimal move, if it has 2, we have to calculate the length for both options. Becasue of the advantage of consecutive moves, there are at most 2 paths from any key on the numeric pad to any other key.
- With this setting the algorithm is rather straight forward:
- Start with the (numeric) code.
- Tokenize the code, i.e. create the movments needed. For instance the code
540A
translates to[A,5], [5,4], [4,0], [0,A]
representing the movements needed. - Use the lookup table created before to get all key presses on the (next) directional pad.
- For each keypress sequence just generated recurse into the funciton increasing the depth counter until you reach the final depth.
- If there was more than one option, calculate both options and keep track of the minimum.
- Add the result of the minimum path to the current string length.
- Once you are at the final depth simply count the number of keys and stop.
- We must keep a cache of lengths of certain key sequences at eahc depth, otherwise
we would end up in way too many recursions. That is if we found out that at depth 4 a
key seqeunce of
v|A
requires x keys at the final depth we store this information. The next time we need to calculate the number of keys needed forv|A
at depth 4, we do not recurse again, but ismply use the cached value.
make_pad <- function(type = c("num", "dir")) {
type <- match.arg(type)
if (type == "num") {
G <- make_lattice(c(3L, 4L), directed = TRUE, mutual = TRUE)
V(G)$name <- c("--", "0", "A", 1:9)
E(G)$name <- c(">", "^", ">", "<", "^", "<", "^",
rep(c(">", "^", "v", ">", "<", "^", "v", "<", "^", "v"), 2L),
">", "v", ">", "<", "v", "<", "v")
} else if (type == "dir") {
G <- make_lattice(c(3L, 2L), directed = TRUE, mutual = TRUE)
V(G)$name <- c("<", "v", ">", "--", "^", "A")
E(G)$name <- c(">", "^", ">", "<", "^", "<", "^",
">", "v", ">", "<", "v", "<", "v")
}
V(G)$shape <- "square"
V(G)$color <- "lightgray"
V(G)$size <- 50
E(G)$arrow.size <- 0
costs <- c(">" = 1, "^" = 2, "v" = 3, "<" = 4)
E(G)$weight <- costs[E(G)$name]
G %>%
delete_edges(incident(G, "--")) %>%
set_graph_attr("layout", layout_on_grid(G, width = 3L, height = 4L))
}
plot_graphs <- function(graphs) {
op <- par(mfrow = 1:2)
on.exit(par(op))
for (i in graphs) {
plot(i)
}
}
get_dup_length <- function(path) {
## idea find paths which have many moves into the same direction
nodes <- str_split(path, "\\|")[[1L]]
len <- rle(nodes)$lengths
length(len) * (length(nodes) - max(len))
}
get_shortest_paths <- function(G) {
map(V(G)[name != "--"]$name, function(start) {
path <- all_shortest_paths(G, start, V(G)[name != "--"], mode = "out")
tibble(from = start,
to = map_chr(path$vpaths, ~ tail(.x, 1L)$name),
path = map_chr(path$epaths,
~ E(G)[.x]$name %>%
c("A") %>%
paste(collapse = "|")),
dup_len = map_int(path, get_dup_length)
)
}) %>%
list_rbind() %>%
slice_min(dup_len, n = 1L, by = c(from, to))
}
tokenize_path <- function(path) {
nodes <- str_split(path, "\\|")[[1L]]
cbind(c("A", head(nodes, -1L)),
nodes) %>%
apply(1, paste, collapse = "|")
}
graphs <- c("num", "dir") %>%
set_names() %>%
map(make_pad)
shortest_paths <- map(graphs, get_shortest_paths) %>%
list_rbind() %>%
mutate(start = paste(from, to, sep = "|"),
end = path, .keep = "none") %>%
summarize(path = list(end), .by = start) %>%
deframe()
get_input_length <- function(start, max_depth, shortest_paths) {
cache <- vector("list", max_depth + 2L)
get_next_sequence <- function(old_path, depth) {
if (old_path %in% names(cache[[depth + 1L]])) {
res <- cache[[depth + 1L]][[old_path]]
} else {
if (depth == max_depth + 1L) {
res <- str_remove_all(old_path, "\\|") %>%
str_length() %>%
as.integer64()
} else {
tokens <- tokenize_path(old_path)
res <- as.integer64(0L)
for (i in seq_along(tokens)) {
new_path <- shortest_paths[[tokens[[i]]]]
new_paths_lengths <- map(new_path, get_next_sequence, depth + 1L) %>%
do.call(c, .)
res <- res + min(new_paths_lengths)
}
}
res <- res %>%
set_names(old_path)
## need this slightly awkward `if` because I cannot pre fill a list with
## an empty int64 (if I try as.integer64(NULL) and `c` the results it gets
## messed up)
if (is.null(cache[[depth + 1L]])) {
cache[[depth + 1L]] <<- res
} else {
cache[[depth + 1L]] <<- c(cache[[depth + 1L]],
res)
}
}
res
}
res <- get_next_sequence(start, 0L)
res
}
calculate_complexity <- function(codes, max_depth, shortest_paths) {
map(codes, function(code) {
int_code <- paste(code %>% head(-1L),
collapse = "") %>%
as.integer64()
code_len <- get_input_length(paste(code, collapse = "|"),
max_depth, shortest_paths)
int_code * code_len
}) %>%
do.call(c, .) %>%
as.integer64() %>%
sum()
}
calculate_complexity(puzzle_data, 2L, shortest_paths)
## integer64
## [1] 278568
2.2 Part 2
2.2.1 Description
— Part Two —
Just as the missing Historian is released, The Historians realize that a second member of their search party has also been missing this entire time!
A quick life-form scan reveals the Historian is also trapped in a locked area of the ship. Due to a variety of hazards, robots are once again dispatched, forming another chain of remote control keypads managing robotic-arm-wielding robots.
This time, many more robots are involved. In summary, there are the following keypads:
- One directional keypad that you are using.
- 25 directional keypads that robots are using.
- One numeric keypad (on a door) that a robot is using.
The keypads form a chain, just like before: your directional keypad controls a robot which is typing on a directional keypad which controls a robot which is typing on a directional keypad… and so on, ending with the robot which is typing on the numeric keypad.
The door codes are the same this time around; only the number of robots and directional keypads has changed.
Find the fewest number of button presses you’ll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?
2.2.2 Solution
calculate_complexity(puzzle_data, 25L, shortest_paths)
## integer64
## [1] 341460772681012