1 Setup
1.1 Libraries
library(httr)
library(xml2)
library(magrittr)
library(tibble)
library(dplyr)
library(purrr)
library(tidyr)
library(glue)
library(stringr)
library(R6)
1.2 Retrieve Data from AoC
session_cookie <- set_cookies(session = keyring::key_get("AoC-GitHub-Cookie"))
base_url <- paste0("https://adventofcode.com/2021/day/", params$task_nr)
puzzle <- GET(base_url,
session_cookie) %>%
content(encoding = "UTF-8") %>%
xml_find_all("///article") %>%
lapply(as.character)
## use curly braces in the last pipe to avoid that . is additionally added
## as the first argument
puzzle_data <- GET(paste0(base_url, "/input"),
session_cookie) %>%
content(encoding = "UTF-8") %>%
str_split("\n") %>%
`[[`(1) %>%
str_split("") %>%
head(n = -1L) ## remove empty string at end
2 Puzzle Day 10
2.1 Part 1
2.1.1 Description
— Day 10: Syntax Scoring —
You ask the submarine to determine the best route out of the deep-sea cave, but it only replies:
Syntax error in navigation subsystem on line: all of them
All of them?! The damage is worse than you thought. You bring up a copy of the navigation subsystem (your puzzle input).
The navigation subsystem syntax is made of several lines containing chunks. There are one or more chunks on each line, and chunks contain zero or more other chunks. Adjacent chunks are not separated by any delimiter; if one chunk stops, the next chunk (if any) can immediately start. Every chunk must open and close with one of four legal pairs of matching characters:
-
If a chunk opens with
(
, it must close with)
. -
If a chunk opens with
[
, it must close with]
. -
If a chunk opens with
{
, it must close with}
. -
If a chunk opens with
<
, it must close with>
.
So, ()
is a legal chunk that contains no other chunks, as is []
. More complex but valid chunks include ([])
, {()()()}
, <([{}])>
, [<>({}){}[([])<>]]
, and even (((((((((())))))))))
.
Some lines are incomplete, but others are corrupted. Find and discard the corrupted lines first.
A corrupted line is one where a chunk closes with the wrong character - that is, where the characters it opens and closes with do not form one of the four legal pairs listed above.
Examples of corrupted chunks include (]
, {()()()>
, (((()))}
, and <([]){()}[{}])
. Such a chunk can appear anywhere within a line, and its presence causes the whole line to be considered corrupted.
For example, consider the following navigation subsystem:
[({(<(())[]>[[{[]{<()<>>
[(()[<>])]({[<{<<[]>>(
{([(<{}[<>[]}>{[]{[(<()>
(((({<>}<{<{<>}{[]{[]{}
[[<[([]))<([[{}[[()]]]
[{[{({}]{}}([{[{{{}}([]
{<[[]]>}<{[{[{[]{()[[[]
[<(<(<(<{}))><([]([]()
<{([([[(<>()){}]>(<<{{
<{([{{}}[<[[[<>{}]]]>[]]
Some of the lines aren’t corrupted, just incomplete; you can ignore these lines for now. The remaining five lines are corrupted:
-
{([(<{}[<>[]}>{[]{[(<()>
- Expected]
, but found}
instead. -
[[<[([]))<([[{}[[()]]]
- Expected]
, but found)
instead. -
[{{({}}([{[{{{}}([]
- Expected)
, but found]
instead. -
[<(<(<(<{}))><(
instead. -
<{([([[(<>()){}]>(<<{{
- Expected]
, but found>
instead.
Stop at the first incorrect closing character on each corrupted line.
Did you know that syntax checkers actually have contests to see who can get the high score for syntax errors in a file? It’s true! To calculate the syntax error score for a line, take the first illegal character on the line and look it up in the following table:
-
)
:3
points. -
]
:57
points. -
}
:1197
points. -
>
:25137
points.
In the above example, an illegal )
was found twice (2*3 = 6
points), an illegal ]
was found once (57
points), an illegal }
was found once (1197
points), and an illegal >
was found once (25137
points). So, the total syntax error score for this file is 6+57+1197+25137 = 26397
points!
Find the first illegal character in each corrupted line of the navigation subsystem. What is the total syntax error score for those errors?
2.1.2 Solution
My first intuition was to use RegEx, but after reading some SO Answers I am not sure whether RegEx is the right tool. The answer shows some funky posisbilities to solve it via RegEx, but hey, why going through all this hassle. Instead I
will use a good old loop (you may have guessed, purrr::reduce
to the rescue, simply
because of its nifty rlang::done
support).
The idea is that we loop through the string and maintain a LIFO stack of the opened brackets. When we encounter a closing bracket, we check whether it has a corresponding open bracket on the top of the stack. If this is not the case, we indicate an error.
## a naive implementation of a stack
Stack <- R6Class(
"qstack",
public = list(
initialize = function(init_size = 1000L) {
private$.stack <- rep(list(NULL), init_size)
private$.head <- 0L
private$.init_size <- private$.size <- as.integer(init_size)
},
push = function(elem) {
if (private$.head == private$.size) {
message(
sprintf(paste("stack size is too small -",
"trying to reallociate %d more slots"),
private$.init_size))
private$.stack <- c(private$.stack,
rep(list(NULL), private$.init_size))
private$.size <- private$.size + private$.init_size
}
private$.head <- private$.head + 1L
private$.stack[[private$.head]] <- elem
invisible(self)
},
pop = function() {
if (private$.head == 0) {
NULL
} else {
el <- private$.stack[[private$.head]]
private$.stack[private$.head] <- list(NULL)
private$.head <- private$.head -1
el
}
},
size = function() {
private$.head
},
max_size = function() {
private$.size
},
print = function() {
if (private$.head == 0L) {
cat("# Empty stack\n")
} else {
indent <- " "
cat(glue("# Stack with {private$.head} element(s)"), "\n")
str <- capture.output(private$.stack[seq(1, private$.head, 1L)])
str <- paste0(indent, str)
str <- str_replace_all(str, glue("^{indent}$"),
glue("\n{indent}^^^\n", .trim = FALSE))
str[length(str)] <- ""
str <- str_replace(
str,
glue("{indent}(\\[\\[{private$.head}\\]\\])"),
"--> \\1")
cat(str, sep = "\n")
}
}
),
private = list(
.stack = NULL,
.head = NA_integer_,
.init_size = NA_integer_,
.size = NA_integer_
)
)
brackets_data <- tribble(
~ open, ~ close, ~value_missing, ~value_adding,
"(", ")", 3L, 1L,
"[", "]", 57L, 2L,
"{", "}", 1197L, 3L,
"<", ">", 25137L, 4L)
is_opening <- function(chr) {
chr %in% brackets_data$open
}
match_brackets <- function(a, b) {
cls <- brackets_data %>%
filter(close == b)
does_match <- cls %>%
filter(open == a) %>%
nrow() == 1L
if (does_match) {
0L
} else {
cls %>%
pull(value_missing)
}
}
get_closing_value <- function(a) {
brackets_data %>%
filter(open == a) %>%
pull(value_adding)
}
check_line <- function(line) {
stack <- Stack$new(length(line))
check <- function(value, chr) {
if (is_opening(chr)) {
stack$push(chr)
res <- 0L
} else {
el <- stack$pop()
res <- match_brackets(el, chr)
}
if (res > 0) {
done(list(result = res, stack = stack))
} else {
list(result = res, stack = stack)
}
}
reduce(line, check, .init = list(result = 0L, stack = stack))
}
res <- map(puzzle_data, check_line)
sum(map_int(res, pluck, "result"))
## [1] 311949
2.2 Part 2
2.2.1 Description
— Part Two —
Now, discard the corrupted lines. The remaining lines are incomplete.
Incomplete lines don’t have any incorrect characters - instead, they’re missing some closing characters at the end of the line. To repair the navigation subsystem, you just need to figure out the sequence of closing characters that complete all open chunks in the line.
You can only use closing characters ()
, ]
, }
, or >
), and you must add them in the correct order so that only legal pairs are formed and all chunks end up closed.
In the example above, there are five incomplete lines:
-
[({(<(())[]>[[{[]{<()<>>
- Complete by adding}}]])})]
. -
(()[<>])
. -
(((({<>}<{<{<>}{[]{
- Complete by adding}}>}>))))
. -
{<[[]]>}<{[{[{[]{()[[[]
- Complete by adding]]}}]}]}>
. -
<{([{{}}[<[[[<>{}]]]>[]]
- Complete by adding])}>
.
Did you know that autocomplete tools also have contests? It’s true! The score is determined by considering the completion string character-by-character. Start with a total score of 0
. Then, for each character, multiply the total score by 5 and then increase the total score by the point value given for the character in the following table:
-
)
:1
point. -
]
:2
points. -
}
:3
points. -
>
:4
points.
So, the last completion string above - ])}>
- would be scored as follows:
-
Start with a total score of
0
. -
Multiply the total score by 5 to get
0
, then add the value of]
(2) to get a new total score of2
. -
Multiply the total score by 5 to get
10
, then add the value of)
(1) to get a new total score of11
. -
Multiply the total score by 5 to get
55
, then add the value of}
(3) to get a new total score of58
. -
Multiply the total score by 5 to get
290
, then add the value of>
(4) to get a new total score of294
.
The five lines’ completion strings have total scores as follows:
-
}}]])})]
-288957
total points. -
)}>]})
-5566
total points. -
}}>}>))))
-1480781
total points. -
]]}}]}]}>
-995444
total points. -
])}>
-294
total points.
Autocomplete tools are an odd bunch: the winner is found by sorting all of the scores and then taking the middle score. (There will always be an odd number of scores to consider.) In this example, the middle score is 288957
because there are the same number of scores smaller and larger than it.
Find the completion string for each incomplete line, score the completion strings, and sort the scores. What is the middle score?
2.2.2 Solution
We filter the results from part 1 by dropping corrupt and valid codes, which leaves us with incomplete codes (valid codes have an empty stack as all opening brackets were dutifully closed). For those, we just close each bracket still on the stack and update the penailty formula as indicated.
## Please note the R 4.1. shortcut for anonymous function
incomplete <- Filter(\(r) r$result == 0L & r$stack$size() > 0, res)
get_score <- function(res) {
sum <- 0
while(res$stack$size() > 0) {
sum <- sum * 5 + get_closing_value(res$stack$pop())
}
sum
}
map_dbl(incomplete, get_score) %>%
median()
## [1] 3042730309