library(tidyverse)
Day 2
Advent of Code: Worked Solutions
Setup
Import libraries:
Read text input from file into a list of numeric vectors:
<- read_lines("../input/day02.txt") |>
input str_split(" ") |>
map(parse_number)
Part 1
Define a function to determine whether a sequence is valid (all values are increasing or all are decreasing, with integer differences between 1 and 3):
<- function(seq) {
is_valid <- head(seq, -1) - tail(seq, -1)
gaps all(gaps < 0) | all(gaps > 0)) & all(abs(gaps) <= 3)
( }
Count the number of safe reports in the puzzle input:
|>
input map_lgl(is_valid) |>
sum()
Part 2
For each report in the input, create a set of variants where a single level from the report is removed at a time. Then, check the validity of each of these altered reports (and the original) & count how many reports are or can become valid:
|>
input map(\(seq) c(list(seq), map(1:length(seq), \(n) discard_at(seq, n)))) |>
map_lgl(\(set) any(map_lgl(set, is_valid))) |>
sum()