02: Red-Nosed Reports

library(mistlecode)

options(scipen = 999)
dt <-
  'input.txt' |>
  readLines() |>
  strsplit(' ') |>
  purrr::map(as.integer)

Part 1

I missed the second condition for a pass at first. Mildly annoying, but not too bad globally.

dt |>
  purrr::map_lgl(\(x) {
    x <- x - lag(x)
    x <- x[!is.na(x)]
    all(abs(x) %in% 1:3) & (all(x < 0) | all(x > 0))
  }) |> 
  sum()
[1] 686

Part 2

I’m really pleased with this. I was trying something more functional, then realized a simple for loop was the way to go and that resulted in a 495 on the leaderboard. It’s also a good example for whatever it’s called that I did with my returns not just being if statements the whole way down.

test <- function(x) {
  x <- x - lag(x)
  x <- x[!is.na(x)]
  all(abs(x) %in% 1:3) & (all(x < 0) | all(x > 0))
}

dt |>
  purrr::map_lgl(\(x) {
    if (test(x)) return(TRUE)
    for(i in seq_along(x)) {
      if (test(x[-i])) return(TRUE)
    }
    return(FALSE)
  }) |> 
  sum()
[1] 717