# Libraries
library(tidyverse)
# Read input from file
<- read_lines("../input/day09.txt", skip_empty_rows = TRUE) input
Day 9
Advent of Code: Worked Solutions
Setup
Part 1
Convert text input into a series of numeric sequences:
<- input |>
seqs str_split("\\s+") |>
map(as.numeric)
Define a function to get the next value in a sequence:
<- function(x) {
extrapolate_next 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:
<- function(x) {
extrapolate_prev 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