library(tidyverse)
Day 10
Advent of Code: Worked Solutions
Setup
Import libraries:
Read input from file:
<- read_lines("../input/day10.txt") |>
input str_split("")
Part 1
Define our open/close bracket pairs and the scores for each type:
<- c("(", "[", "{", "<")
b_open <- c(")", "]", "}", ">")
b_close <- c(set_names(b_close, b_open), set_names(b_open, b_close))
b_pairs <- set_names(c(3, 57, 1197, 25137), b_close) b_score
Define a function to move through a line, add/remove brackets to a stack, and return the first invalid closing bracket found.
<- function(x) {
check_line <- c()
stack for (chr in x) {
if (chr %in% b_open)
<- c(stack, chr)
stack else if (tail(stack, 1) == b_pairs[chr])
<- head(stack, -1)
stack else
return(chr)
} }
Identify which lines have mistakes:
<- input |>
scanned map(check_line)
Sum the total score for all mistakes:
|>
scanned unlist() |>
map_int(~ b_score[[.x]]) |>
sum()
Part 2
Modify the point values for each closing bracket:
<- set_names(1:4, b_close) b_score
Alter the line-scanning function to return the autocomplete brackets:
<- function(x) {
complete_line <- c()
stack for (chr in x) {
if (chr %in% b_open)
<- c(stack, chr)
stack else if (tail(stack, 1) == b_pairs[chr])
<- head(stack, -1)
stack
}
return(unname(b_pairs[rev(stack)]))
}
Define a function to score a given completion string:
<- \(x) reduce(x, ~ .x * 5 + b_score[[.y]], .init = 0) score_autocomplete
Autocomplete all non-error inputs, score the results, then take the median:
<- map_lgl(scanned, is.null)
is_incomplete
|>
input keep(is_incomplete) |>
map(complete_line) |>
map_dbl(score_autocomplete) |>
median()