1 Setup
1.1 Libraries
library(httr)
library(xml2)
library(magrittr)
library(dplyr)
library(purrr)
library(stringr)
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/", 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)
}
res <- text_block %>%
str_extract_all("[A-Z]{2}|\\d+") %>%
map(~ list(edges = tibble(from = .x[[1L]], to = tail(.x, -2L)),
vertices = tibble(id = .x[[1L]], valve = as.integer(.x[[2L]]))))
edges <- map(res, "edges") %>%
list_rbind() %>%
mutate(tmp = pmax(from, to),
from = pmin(from, to),
to = tmp,
tmp = NULL) %>%
distinct()
vertices <- map(res, "vertices") %>%
list_rbind()
list(edges = edges,
vertices = vertices)
}
puzzle_data <- local({
GET(paste0(base_url, "/input"),
session_cookie) %>%
content(encoding = "UTF-8") %>%
parse_puzzle_data()
})
2 Puzzle Day 16
2.1 Part 1
2.1.1 Description
— Day 16: Proboscidea Volcanium —
The sensors have led you to the origin of the distress signal: yet another handheld device, just like the one the Elves gave you. However, you don’t see any Elves around; instead, the device is surrounded by elephants! They must have gotten lost in these tunnels, and one of the elephants apparently figured out how to turn on the distress signal.
The ground rumbles again, much stronger this time. What kind of cave is this, exactly? You scan the cave with your handheld device; it reports mostly igneous rock, some ash, pockets of pressurized gas, magma… this isn’t just a cave, it’s a volcano!
You need to get the elephants out of here, quickly. Your device estimates that you have 30 minutes before the volcano erupts, so you don’t have time to go back out the way you came in.
You scan the cave for other options and discover a network of pipes and pressure-release valves. You aren’t sure how such a system got into a volcano, but you don’t have time to complain; your device produces a report (your puzzle input) of each valve’s flow rate if it were opened (in pressure per minute) and the tunnels you could use to move between the valves.
There’s even a valve in the room you and the elephants are currently standing in labeled AA. You estimate it will take you one minute to open a single valve and one minute to follow any tunnel from one valve to another. What is the most pressure you could release?
For example, suppose you had the following scan output:
Valve AA has flow rate=0; tunnels lead to valves DD, II, BB
Valve BB has flow rate=13; tunnels lead to valves CC, AA
Valve CC has flow rate=2; tunnels lead to valves DD, BB
Valve DD has flow rate=20; tunnels lead to valves CC, AA, EE
Valve EE has flow rate=3; tunnels lead to valves FF, DD
Valve FF has flow rate=0; tunnels lead to valves EE, GG
Valve GG has flow rate=0; tunnels lead to valves FF, HH
Valve HH has flow rate=22; tunnel leads to valve GG
Valve II has flow rate=0; tunnels lead to valves AA, JJ
Valve JJ has flow rate=21; tunnel leads to valve II
All of the valves begin closed. You start at valve AA, but it must be damaged or jammed or something: its flow rate is 0, so there’s no point in opening it. However, you could spend one minute moving to valve BB and another minute opening it; doing so would release pressure during the remaining 28 minutes at a flow rate of 13, a total eventual pressure release of 28 * 13 = 364. Then, you could spend your third minute moving to valve CC and your fourth minute opening it, providing an additional 26 minutes of eventual pressure release at a flow rate of 2, or 52 total pressure released by valve CC.
Making your way through the tunnels like this, you could probably open many or all of the valves by the time 30 minutes have elapsed. However, you need to release as much pressure as possible, so you’ll need to be methodical. Instead, consider this approach:
== Minute 1 ==
No valves are open.
You move to valve DD.
== Minute 2 ==
No valves are open.
You open valve DD.
== Minute 3 ==
Valve DD is open, releasing 20 pressure.
You move to valve CC.
== Minute 4 ==
Valve DD is open, releasing 20 pressure.
You move to valve BB.
== Minute 5 ==
Valve DD is open, releasing 20 pressure.
You open valve BB.
== Minute 6 ==
Valves BB and DD are open, releasing 33 pressure.
You move to valve AA.
== Minute 7 ==
Valves BB and DD are open, releasing 33 pressure.
You move to valve II.
== Minute 8 ==
Valves BB and DD are open, releasing 33 pressure.
You move to valve JJ.
== Minute 9 ==
Valves BB and DD are open, releasing 33 pressure.
You open valve JJ.
== Minute 10 ==
Valves BB, DD, and JJ are open, releasing 54 pressure.
You move to valve II.
== Minute 11 ==
Valves BB, DD, and JJ are open, releasing 54 pressure.
You move to valve AA.
== Minute 12 ==
Valves BB, DD, and JJ are open, releasing 54 pressure.
You move to valve DD.
== Minute 13 ==
Valves BB, DD, and JJ are open, releasing 54 pressure.
You move to valve EE.
== Minute 14 ==
Valves BB, DD, and JJ are open, releasing 54 pressure.
You move to valve FF.
== Minute 15 ==
Valves BB, DD, and JJ are open, releasing 54 pressure.
You move to valve GG.
== Minute 16 ==
Valves BB, DD, and JJ are open, releasing 54 pressure.
You move to valve HH.
== Minute 17 ==
Valves BB, DD, and JJ are open, releasing 54 pressure.
You open valve HH.
== Minute 18 ==
Valves BB, DD, HH, and JJ are open, releasing 76 pressure.
You move to valve GG.
== Minute 19 ==
Valves BB, DD, HH, and JJ are open, releasing 76 pressure.
You move to valve FF.
== Minute 20 ==
Valves BB, DD, HH, and JJ are open, releasing 76 pressure.
You move to valve EE.
== Minute 21 ==
Valves BB, DD, HH, and JJ are open, releasing 76 pressure.
You open valve EE.
== Minute 22 ==
Valves BB, DD, EE, HH, and JJ are open, releasing 79 pressure.
You move to valve DD.
== Minute 23 ==
Valves BB, DD, EE, HH, and JJ are open, releasing 79 pressure.
You move to valve CC.
== Minute 24 ==
Valves BB, DD, EE, HH, and JJ are open, releasing 79 pressure.
You open valve CC.
== Minute 25 ==
Valves BB, CC, DD, EE, HH, and JJ are open, releasing 81 pressure.
== Minute 26 ==
Valves BB, CC, DD, EE, HH, and JJ are open, releasing 81 pressure.
== Minute 27 ==
Valves BB, CC, DD, EE, HH, and JJ are open, releasing 81 pressure.
== Minute 28 ==
Valves BB, CC, DD, EE, HH, and JJ are open, releasing 81 pressure.
== Minute 29 ==
Valves BB, CC, DD, EE, HH, and JJ are open, releasing 81 pressure.
== Minute 30 ==
Valves BB, CC, DD, EE, HH, and JJ are open, releasing 81 pressure.
This approach lets you release the most pressure possible in 30 minutes with this valve layout, 1651.
Work out the steps to release the most pressure in 30 minutes. What is the most pressure you can release?
2.1.2 Solution
First we construct a graph G from the tunnel layout. We see, that there are valves, which
do not release any pressure. We construct a new complete graph G2 based on G, where
we remove valves with pressure release of zero and add a weight to the edges corresponding
to the path length between the nodes.
Thus, we have a complete graph as input, where the edges correspond to the time needed to move from one node to the other. Then, we can use dynamic programming to find an optimal route. The idea is the following:
- Let \(N\) denote the number of non starting nodes. We then keep track of the currrent
state in list
dpof length \(2 ^ N\). Each entry corresponds to the subset of visited nodes, where we use a bitmask for easier indexing. For instance, assume that \(N=4\) then \(9 = 1001_2\) would indicate that we visited the first and the fourth node, but not the second nor the third. - Each state is represented by a named vector of reached nodes (the names) with their
current gain (the value). We set the initial state to
c(starting_node = 0)indicating that we just reached the start and have no gain yet. Likewise we also store the costs to reach each node in listcosts. - We loop over all the states and update them in the following way:
- If we did not reach the state yet, skip it.
- If we reached the state in a previous iteration, construct all possible extensions.
That is take all nodes visited in the current state, look at all nodes not visited yet
for the given state. As we are using bitmasks, this can be cone by looking at the
ithbit: if it is set, this node was already visited and we skip, otherwise it is a valid candidate. - For each valid neighbor calculate the costs to reach it. If the costs do not exceed
the budget, calculate the new gain. The gain is the pressure release multiplied by
the remaining budget (which is in fact the remaining time) plus the gain reached so
far (as stored in
dp). - If the new gain is higher than the previously stored gain, update the gain in
dpaccordingly.
- The result is the maximum gain.
create_graph <- function(vertices, edges) {
G <- graph_from_data_frame(edges, FALSE, vertices)
V(G)$shape <- if_else(V(G)$name == "AA", "square", "circle")
V(G)$color <- case_when(
V(G)$name == "AA" ~"forestgreen",
V(G)$valve == 0L ~ "firebrick",
TRUE ~ "beige")
V(G)$size <- 10
V(G)$label.color <- if_else(V(G)$valve == 0L | V(G)$name == "AA", "white", "black")
G
}
contract_graph <- function(G, start = "AA") {
keep <- V(G)[V(G)$valve != 0 | V(G)$name == start]
keep_names <- names(keep)
d <- distances(
G,
v = keep,
to = keep,
mode = "out"
)
edges <- c()
weights <- c()
n <- length(keep_names)
for (i in 2:n) {
for (j in 1:i) {
if (i != j && is.finite(d[i, j])) {
edges <- c(edges, keep_names[i], keep_names[j])
weights <- c(weights, d[i, j])
}
}
}
G2 <- make_graph(
edges,
directed = FALSE
)
E(G2)$weight <- weights
V(G2)$valve <- V(G)$valve[match(V(G2)$name, V(G)$name)]
V(G2)$shape <- V(G)$shape[match(V(G2)$name, V(G)$name)]
V(G2)$color <- V(G)$color[match(V(G2)$name, V(G)$name)]
V(G2)$label.color <- V(G)$label.color[match(V(G2)$name, V(G)$name)]
V(G2)$size <- 10
V(G2)$type <- "node"
V(G2)[V(G2)$name == start]$type <- "start"
G2
}
popcount <- function(n) {
bits <- as.integer(intToBits(n))
sum(bits)
}
find_valve_strategy <- function(vertices, edges, budget) {
G <- create_graph(puzzle_data$vertices, puzzle_data$edges) %>%
contract_graph()
start <- V(G)[V(G)$type == "start"]$name
nodes <- setdiff(V(G)$name, start)
w <- V(G)$valve[match(nodes, V(G)$name)]
names(w) <- nodes
dist <- distances(G)
N <- length(nodes)
B0 <- budget
dp <- vector("list", 2 ^ N)
cost <- vector("list", 2 ^ N)
el <- 0L %>%
set_names(start)
dp[[1L]] <- el
cost[[1L]] <- el
for (mask in 0:(2L ^ N - 1L)) {
## iterate over all possible selections, mask is a bit mask if bit i is 1
## then node nodes[i] is visited in this iteration
idx <- mask + 1L
if (is.null(dp[[idx]])) {
## no state yet
next
}
n_visited <- popcount(mask) ## number of selected nodes
for (v in names(dp[[idx]])) {
for (u in 1:N) {
nb_mask <- bitwShiftL(1L, u - 1L)
if (bitwAnd(mask, nb_mask) != 0L) {
## neighbor is already visited
next
}
new_mask <- bitwOr(mask, nb_mask)
new_idx <- new_mask + 1L
new_cost <- cost[[idx]][v] + dist[v, nodes[u]]
new_k <- n_visited + 1L
B_remain <- B0 - new_cost - new_k
if (B_remain < 0L) {
next
}
new_gain <- dp[[idx]][v] + B_remain * w[nodes[u]]
if (is.null(dp[[new_idx]]) || coalesce(dp[[new_idx]][nodes[u]], 0L) < new_gain) {
dp[[new_idx]][nodes[u]] <- new_gain
cost[[new_idx]][nodes[u]] <- new_cost
}
}
}
}
max(unlist(dp))
}
find_valve_strategy(puzzle_data$vertices, puzzle_data$edges, 30L)
## [1] 1828
2.2 Part 2
2.2.1 Description
— Part Two —
You’re worried that even with an optimal approach, the pressure released won’t be enough. What if you got one of the elephants to help you?
It would take you 4 minutes to teach an elephant how to open the right valves in the right order, leaving you with only 26 minutes to actually execute your plan. Would having two of you working together be better, even if it means having less time? (Assume that you teach the elephant before opening any valves yourself, giving you both the same full 26 minutes.)
In the example above, you could teach the elephant to help you as follows:
== Minute 1 ==
No valves are open.
You move to valve II.
The elephant moves to valve DD.
== Minute 2 ==
No valves are open.
You move to valve JJ.
The elephant opens valve DD.
== Minute 3 ==
Valve DD is open, releasing 20 pressure.
You open valve JJ.
The elephant moves to valve EE.
== Minute 4 ==
Valves DD and JJ are open, releasing 41 pressure.
You move to valve II.
The elephant moves to valve FF.
== Minute 5 ==
Valves DD and JJ are open, releasing 41 pressure.
You move to valve AA.
The elephant moves to valve GG.
== Minute 6 ==
Valves DD and JJ are open, releasing 41 pressure.
You move to valve BB.
The elephant moves to valve HH.
== Minute 7 ==
Valves DD and JJ are open, releasing 41 pressure.
You open valve BB.
The elephant opens valve HH.
== Minute 8 ==
Valves BB, DD, HH, and JJ are open, releasing 76 pressure.
You move to valve CC.
The elephant moves to valve GG.
== Minute 9 ==
Valves BB, DD, HH, and JJ are open, releasing 76 pressure.
You open valve CC.
The elephant moves to valve FF.
== Minute 10 ==
Valves BB, CC, DD, HH, and JJ are open, releasing 78 pressure.
The elephant moves to valve EE.
== Minute 11 ==
Valves BB, CC, DD, HH, and JJ are open, releasing 78 pressure.
The elephant opens valve EE.
(At this point, all valves are open.)
== Minute 12 ==
Valves BB, CC, DD, EE, HH, and JJ are open, releasing 81 pressure.
...
== Minute 20 ==
Valves BB, CC, DD, EE, HH, and JJ are open, releasing 81 pressure.
...
== Minute 26 ==
Valves BB, CC, DD, EE, HH, and JJ are open, releasing 81 pressure.
With the elephant helping, after 26 minutes, the best you could do would release a total of 1707 pressure.
With you and an elephant working together for 26 minutes, what is the most pressure you could release?
2.2.2 Solution
For the second part, we keep the same principle as for part 1 with some additions:
- For both players opening valves we keep an extra
costlist. - Instead of naming the gain / costs with the node names, we name it with a compound key,
consisting of the node of the player and the elephant separated by
|respectively. For instance the cost with nameAT|STmeans that the player is currently at nodeATwhile the elephant is at nodeST. - At each iteration we first iterate over all nodes for the player, updating all costs accordingly and then do the same for the elephant.
- Eventually, we still return the maximum gain over all states.
find_valve_strategy_elephant <- function(vertices, edges, budget) {
G <- create_graph(vertices, edges) %>%
contract_graph()
start <- V(G)[V(G)$type == "start"]$name
nodes <- setdiff(V(G)$name, start)
N <- length(nodes)
w <- V(G)$valve[match(nodes, V(G)$name)]
names(w) <- nodes
dist <- distances(G)
dp <- vector("list", 2L ^ N)
cost1 <- vector("list", 2L ^ N)
cost2 <- vector("list", 2L ^ N)
key0 <- paste(start, start, sep = "|")
dp[[1L]] <- set_names(0L, key0)
cost1[[1L]] <- set_names(0L, key0)
cost2[[1L]] <- set_names(0L, key0)
for (mask in 0:(2 ^ N - 1L)) {
idx <- mask + 1L
if (is.null(dp[[idx]])) {
next
}
visited_count <- popcount(mask)
for (key in names(dp[[idx]])) {
parts <- str_split(key, "\\|")[[1L]]
pos1 <- parts[1L]
pos2 <- parts[2L]
gain_prev <- dp[[idx]][key]
t1_prev <- cost1[[idx]][key]
t2_prev <- cost2[[idx]][key]
for (u_idx in 1:N) {
nb_mask <- bitwShiftL(1L, u_idx - 1L)
if (bitwAnd(mask, nb_mask) != 0L) {
next
}
u <- nodes[u_idx]
# --- Option A: I am opening valve u
t1_new <- t1_prev + dist[pos1, u] + 1L
if (t1_new <= budget) {
new_mask <- bitwOr(mask, nb_mask)
new_idx <- new_mask + 1L
rem1 <- budget - t1_new
gain1 <- gain_prev + rem1 * w[u]
new_key <- paste(u, pos2, sep = "|")
if (is.null(dp[[new_idx]]) ||
is.na(dp[[new_idx]][new_key]) ||
dp[[new_idx]][new_key] < gain1) {
dp[[new_idx]][new_key] <- gain1
cost1[[new_idx]][new_key] <- t1_new
cost2[[new_idx]][new_key] <- t2_prev
}
}
# --- Option B: elephant is opening valve u
t2_new <- t2_prev + dist[pos2, u] + 1L
if (t2_new <= budget) {
new_mask <- bitwOr(mask, nb_mask)
new_idx <- new_mask + 1L
rem2 <- budget - t2_new
gain2 <- gain_prev + rem2 * w[u]
new_key <- paste(pos1, u, sep = "|")
if (is.null(dp[[new_idx]]) ||
is.na(dp[[new_idx]][new_key]) ||
dp[[new_idx]][new_key] < gain2) {
dp[[new_idx]][new_key] <- gain2
cost1[[new_idx]][new_key] <- t1_prev
cost2[[new_idx]][new_key] <- t2_new
}
}
}
}
}
max(unlist(dp))
}
find_valve_strategy_elephant(puzzle_data$vertices, puzzle_data$edges, 26L)
## [1] 2292