2022-04: Camp Cleanup

library(tidyverse)
── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
✔ ggplot2 3.4.0      ✔ purrr   0.3.5 
✔ tibble  3.1.8      ✔ dplyr   1.0.10
✔ tidyr   1.2.1      ✔ stringr 1.4.1 
✔ readr   2.1.3      ✔ forcats 0.5.2 
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
library(data.table)

Attaching package: 'data.table'

The following objects are masked from 'package:dplyr':

    between, first, last

The following object is masked from 'package:purrr':

    transpose
dt <- fread("input.txt", header = FALSE)
# dt <- readLines("input.txt")

This looks bad at first, but it’s not.

Part 1

It took me a minute to figure out how I wanted to work with the data ranges. I started with mutate then lapply then quickly switched to mapply. From there it wrote itself. I then second-guessed my answer and divided by two because I thought I was double reporting the ranges. I cost myself a minute :(

mapply(\(x, y) {
  x <- as.numeric(unlist(strsplit(x, "-")))
  y <- as.numeric(unlist(strsplit(y, "-")))
  
  all(x[1]:x[2] %in% y[1]:y[2]) | all(y[1]:y[2] %in% x[1]:x[2])
}, dt$V1, dt$V2) |>
  unlist() |>
  table() %>%
  .["TRUE"]
TRUE 
 532 

Part 2

38 seconds for part 2! I just had to change all to any.

mapply(\(x, y) {
  x <- as.numeric(unlist(strsplit(x, "-")))
  y <- as.numeric(unlist(strsplit(y, "-")))
  
  any(x[1]:x[2] %in% y[1]:y[2]) | any(y[1]:y[2] %in% x[1]:x[2])
}, dt$V1, dt$V2) |>
  unlist() |>
  table() %>%
  .["TRUE"]
TRUE 
 854