Day 7

Advent of Code: Worked Solutions

About
Date

December 7, 2024

Setup

# Libraries
library(tidyverse)

# Read input from file
input <- read_lines("../input/day07.txt", skip_empty_rows = TRUE) |> 
  str_split(" ") |> 
  map(parse_number)

Part 1

Define calibration functions:

calibrate_operators <- function(seq, target, 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) {
      new_start <- get(f)(seq[1], seq[2])
      new_seq <- c(new_start, tail(seq, -2))
      calibrate_operators(new_seq, target, operators)
    }
  ) |> 
    # If any output is true, the output has been calibrated.
    any()
}

calibration_value <- function(input, output, operators) {
  # Compute calibration for each input-output pair
  is_calibrated <- map2_lgl(
    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:

input_values  <- map(input, tail, -1)
output_values <- map_dbl(input, head, 1)
  
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

concat <- function(x, y) as.numeric(str_c(x, y))

calibration_value(input_values, output_values, c("+", "*", "concat"))
[1] "106016735664498"