library(tidyverse)
Day 9
Advent of Code: Worked Solutions
Setup
Import libraries:
Read text input from file into a numeric vector:
<- scan("../input/day09.txt") input
Define the preamble length parameter:
<- 25 preamble
Part 1
Find the first number in the list (after the preamble) which is not the sum of two of the 25 numbers before it:
<- imap(
invalid_num tail(input, n = -preamble),
~ input[1:preamble - 1 + .y] |>
combn(2, simplify = FALSE) |>
map_dbl(sum) |>
setdiff(x = .x, y = _)
|>
) compact() |>
pluck(1)
Part 2
Define a function that starts at the first index and examines all following subsequences until their sum either equals or exceeds the invalid number. If it’s found, then return the sum of the minimum and maximum index in that range. If it overshoots, start over from the second index (and so on):
<- function(vec, target) {
find_weakness <- 1
idx_start
while (idx_start < length(vec)) {
<- idx_start + 1
idx_end
while (idx_end <= length(vec)) {
<- vec[idx_start:idx_end]
range
if (sum(range) == target)
return(min(range) + max(range))
if (sum(range) > target)
break
<- idx_end + 1
idx_end
}<- idx_start + 1
idx_start
} }
Run on puzzle input:
find_weakness(input, invalid_num)