base R
strings
Author

Ella Kaye

Published

December 4, 2022

Setup

The original challenge

My data

Part 1

Toggle the code
library(aochelpers)
# other options: aoc_input_data_frame(), aoc_input_matrix()
input <- aoc_input_vector(4, 2022)
head(input)
[1] "36-92,35-78" "26-31,25-27" "17-72,16-71" "3-77,76-90"  "20-22,21-87"
[6] "5-75,6-75"  

First, we separate the input into a list, where each element is a vector of length 4 of the integers in the input. The regular expression \D matches any non-digit character, and strsplit splits the input on these. Next, we write a function that takes one of these vectors, and checks whether the range defined by first two integers is contained in the range defined by the second two, or vice versa. Finally, we use sapply to apply this function to each element of the list, and the sum of a logical vector is equivalent to counting how many are TRUE.

Toggle the code
all_ints <- strsplit(input, "\\D")

range_contain <- function(ints) {
  all(ints[1]:ints[2] %in% ints[3]:ints[4]) || all(ints[3]:ints[4] %in% ints[1]:ints[2])
}

sapply(all_ints, range_contain) |> sum()
[1] 494

Part 2

Part 2 is almost identical, except we’re checking for any overlap in the ranges.

Toggle the code
range_overlap <- function(ints) {
  any(ints[1]:ints[2] %in% ints[3]:ints[4])
}

sapply(all_ints, range_overlap) |> sum()
[1] 833

Session info

Toggle
─ Session info ───────────────────────────────────────────────────────────────
 setting  value
 version  R version 4.3.1 (2023-06-16)
 os       macOS Sonoma 14.1
 system   aarch64, darwin20
 ui       X11
 language (EN)
 collate  en_US.UTF-8
 ctype    en_US.UTF-8
 tz       Europe/London
 date     2023-11-18
 pandoc   3.1.1 @ /Applications/RStudio.app/Contents/Resources/app/quarto/bin/tools/ (via rmarkdown)
 quarto   1.4.504 @ /usr/local/bin/quarto

─ Packages ───────────────────────────────────────────────────────────────────
 package     * version    date (UTC) lib source
 aochelpers  * 0.0.0.9000 2023-11-17 [1] local
 sessioninfo * 1.2.2      2021-12-06 [1] CRAN (R 4.3.0)

 [1] /Users/ellakaye/Library/R/arm64/4.3/library
 [2] /Library/Frameworks/R.framework/Versions/4.3-arm64/Resources/library

──────────────────────────────────────────────────────────────────────────────