Day 9

Advent of Code: Worked Solutions

About
Date

December 9, 2023

Setup

# Libraries
library(tidyverse)

# Read input from file
input <- read_lines("../input/day09.txt", skip_empty_rows = TRUE)

Part 1

Convert text input into a series of numeric sequences:

seqs <- input |> 
  str_split("\\s+") |> 
  map(as.numeric)

Define a function to get the next value in a sequence:

extrapolate_next <- function(x) {
  if (all(x == 0))
    return(0)
  else
    return(tail(x, 1) + extrapolate_next(diff(x)))
}

Compute next value of every sequence in the input, then sum the result:

seqs |> 
  map_dbl(extrapolate_next) |> 
  sum()
[1] 1641934234

Part 2

Modify the function to get the preceeding sequence value, rather than the next:

extrapolate_prev <- function(x) {
  if (all(x == 0))
    return(0)
  else
    return(head(x, 1) - extrapolate_prev(diff(x)))
}

Run on puzzle input:

seqs |> 
  map_dbl(extrapolate_prev) |> 
  sum()
[1] 975