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)
}
rules <- text_block %>%
str_remove_all(" bags?| contain|,|\\.") %>%
map(function(rule) {
if (str_detect(rule, "no other")) {
vertices <- tibble(name = str_remove(rule, " no other"))
edges <- tibble(from = character(0L),
to = character(0L),
amt = integer(0L))
} else {
colors <- str_split(rule, " \\d+ ") %>%
extract2(1L)
nrs <- str_extract_all(rule, "\\d+") %>%
extract2(1L)
vertices <- tibble(name = unique(colors))
edges <- tibble(from = colors[1L],
to = colors[-1L],
amt = as.integer(nrs))
}
list(vertices = vertices, edges = edges)
})
list(rules = map(rules, "edges") %>%
list_rbind(),
colors = map(rules, "vertices") %>%
list_rbind() %>%
distinct())
}
puzzle_data <- local({
GET(paste0(base_url, "/input"),
session_cookie) %>%
content(encoding = "UTF-8") %>%
parse_puzzle_data()
})
2 Puzzle Day 7
2.1 Part 1
2.1.1 Description
— Day 7: Handy Haversacks —
You land at the regional airport in time for your next flight. In fact, it looks like you’ll even have time to grab some food: all flights are currently delayed due to issues in luggage processing.
Due to recent aviation regulations, many rules (your puzzle input) are being enforced about bags and their contents; bags must be color-coded and must contain specific quantities of other color-coded bags. Apparently, nobody responsible for these regulations considered how long they would take to enforce!
For example, consider the following rules:
light red bags contain 1 bright white bag, 2 muted yellow bags.
dark orange bags contain 3 bright white bags, 4 muted yellow bags.
bright white bags contain 1 shiny gold bag.
muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.
shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags.
dark olive bags contain 3 faded blue bags, 4 dotted black bags.
vibrant plum bags contain 5 faded blue bags, 6 dotted black bags.
faded blue bags contain no other bags.
dotted black bags contain no other bags.
These rules specify the required contents for 9 bag types. In this example, every faded blue bag is empty, every vibrant plum bag contains 11 bags (5 faded blue and 6 dotted black), and so on.
You have a shiny gold bag. If you wanted to carry it in at least one other bag, how many different bag colors would be valid for the outermost bag? (In other words: how many colors can, eventually, contain at least one shiny gold bag?)
In the above rules, the following options would be available to you:
-
A
bright whitebag, which can hold yourshiny goldbag directly. -
A
muted yellowbag, which can hold yourshiny goldbag directly, plus some other bags. -
A
dark orangebag, which can holdbright whiteandmuted yellowbags, either of which could then hold yourshiny goldbag. -
A
light redbag, which can holdbright whiteandmuted yellowbags, either of which could then hold yourshiny goldbag.
So, in this example, the number of bag colors that can eventually contain at least one shiny gold bag is 4.
How many bag colors can eventually contain at least one shiny gold bag? (The list of rules is quite long; make sure you get all of it.)
2.1.2 Solution
We construct a graph from the rule set. Each color represent a vertex and colors are connected if one color may contain the other. Then we have to count the number of unique ancestors.
construct_graph <- function(rules) {
G <- graph_from_data_frame(rules$rules, vertices = rules$colors)
}
count_ancestors <- function(G, target = "shiny gold") {
vid <- which(V(G)$name == target)
ancestors <- subcomponent(G, vid, mode = "in")
ancestors <- setdiff(ancestors, vid)
length(ancestors)
}
G <- construct_graph(puzzle_data)
count_ancestors(G)
## [1] 144
2.2 Part 2
2.2.1 Description
— Part Two —
It’s getting pretty expensive to fly these days - not because of ticket prices, but because of the ridiculous number of bags you need to buy!
Consider again your shiny gold bag and the rules from the above example:
-
faded bluebags contain0other bags. -
dotted blackbags contain0other bags. -
vibrant plumbags contain11other bags: 5faded bluebags and 6dotted blackbags. -
dark olivebags contain7other bags: 3faded bluebags and 4dotted blackbags.
So, a single shiny gold bag must contain 1 dark olive bag (and the 7 bags within it) plus 2 vibrant plum bags (and the 11 bags within each of those): 1 + 1*7 + 2 + 2*11 = 32 bags!
Of course, the actual rules have a small chance of going several levels deeper than this example; be sure to count all of the bags, even if the nesting becomes topologically impractical!
Here’s another example:
shiny gold bags contain 2 dark red bags.
dark red bags contain 2 dark orange bags.
dark orange bags contain 2 dark yellow bags.
dark yellow bags contain 2 dark green bags.
dark green bags contain 2 dark blue bags.
dark blue bags contain 2 dark violet bags.
dark violet bags contain no other bags.
In this example, a single shiny gold bag must contain 126 other bags.
How many individual bags are required inside your single shiny gold bag?
2.2.2 Solution
We need to sort the graph topologically and move from the leaves upwards until we reach the “root” (i.e. the shiny gold bag). While moving upwards we sum the children weights multiplied by the respective edges weights (+1 coounting for the parent bag as well).
count_bags <- function(G, root = "shiny gold") {
vid <- which(V(G)$name == root)
reach <- subcomponent(G, vid, mode = "out")
sg <- induced_subgraph(G, vids = reach)
ord <- topo_sort(sg, mode = "out")
S <- integer(vcount(sg))
for (v in rev(as.integer(ord))) {
e_out <- incident(sg, v, mode = "out")
if (length(e_out) == 0L) {
S[v] <- 0L
} else {
w <- edge_attr(sg, "amt", index = e_out)
targets <- ends(sg, e_out, names = FALSE)[, 2L]
S[v] <- sum(w * (1 + S[as.integer(targets)]))
}
}
S[which(V(sg)$name == root)]
}
count_bags(G)
## [1] 5956