# Libraries
library(tidyverse)
# Read input from file
<- read_lines("../input/day07.txt", skip_empty_rows = TRUE) |>
input str_split(" ") |>
map(parse_number)
Day 7
Advent of Code: Worked Solutions
Setup
Part 1
Define calibration functions:
<- function(seq, target, operators) {
calibrate_operators
# If the end of the list has been reached or the target is already overshot, exit
if (length(seq) == 1)
return(seq == target)
else if (seq[1] > target)
return(FALSE)
# Recursively compare the first two items of the seq using each operator
map_lgl(
operators,
\(f) {<- get(f)(seq[1], seq[2])
new_start <- c(new_start, tail(seq, -2))
new_seq calibrate_operators(new_seq, target, operators)
}|>
) # If any output is true, the output has been calibrated.
any()
}
<- function(input, output, operators) {
calibration_value # Compute calibration for each input-output pair
<- map2_lgl(
is_calibrated
input,
output, ~ calibrate_operators(.x, .y, operators = operators)
)
# Sum the calibrated outputs
|>
output keep(is_calibrated) |>
sum() |>
format(scientific = FALSE)
}
Compute calibration of the puzzle input:
<- map(input, tail, -1)
input_values <- map_dbl(input, head, 1)
output_values
calibration_value(input_values, output_values, c("+", "*"))
[1] "12940396350192"
Part 2
Add a new concatenation operator and re-run the calibration on the puzzle input
<- function(x, y) as.numeric(str_c(x, y))
concat
calibration_value(input_values, output_values, c("+", "*", "concat"))
[1] "106016735664498"