Day 2

Advent of Code: Worked Solutions

About
Date

December 2, 2024

Setup

Import libraries:

library(tidyverse)

Read text input from file into a list of numeric vectors:

input <- read_lines("../input/day02.txt") |> 
  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):

is_valid <- function(seq) {
  gaps <- head(seq, -1) - tail(seq, -1)
  (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()