# Libraries
library(tidyverse)
# Read input from file
<- read_lines("../input/day02.txt") |>
input map(~parse_number(str_split_1(.x, " ")))
Day 2
Advent of Code: Worked Solutions
Setup
Part 1
# Compute difference between consecutive integers
<- function(seq)
seq_gaps head(lead(seq) - seq, -1)
# Check whether the sequence is incr/decr with gaps between 1 and 3
<- function(gaps)
gaps_are_valid all(gaps < 0) | all(gaps > 0)) & all(between(abs(gaps), 1, 3))
(
# Count number of safe reports
|>
input map(seq_gaps) |>
map_lgl(gaps_are_valid) |>
sum()
[1] 306
Part 2
tibble(input) |>
# For each report, create a set of versions where each level is removed
mutate(
id = row_number(),
mod = map(input, \(seq) map(1:length(seq), \(n) seq[-c(n)])),
|>
) unnest(mod) |>
# Check validity of each report and its altered versions
mutate(
report_is_safe = map_lgl(input, ~ gaps_are_valid(seq_gaps(.x))),
mod_is_safe = map_lgl(mod, ~ gaps_are_valid(seq_gaps(.x))),
is_safe = report_is_safe | mod_is_safe
|>
) summarize(is_safe = any(is_safe), .by = id) |>
# Count all safe reports
summarize(total = sum(is_safe)) |>
pull()
[1] 366