2016-04: Security Through Obscurity

library(stringi)
dt <- readLines("input.txt")

Part 1

stri_extract_all_regex(dt, "[a-z]+") |>
  lapply(function(x) {
    x <- paste0(x, collapse = "") |>
      strsplit("") |>
      unlist()
    check <- x[(length(x) - 4):length(x)]
    x <- x[1:(length(x) - 4)]
    x <- sort(table(x), decreasing = TRUE)[1:5]
    
    check <- paste0(check, collapse = "")
    x <- paste0(names(x), collapse = "")
    
    if(x == check) { return(TRUE) }
    return(FALSE)
  }) |>
  unlist() -> tmp

dt[tmp] |>
  stri_extract_all_regex("[0-9]*", simplify = TRUE) |>
  as.numeric() |>
  sum(na.rm = TRUE)
[1] 361724

Part 2

x <- lapply(dt[tmp], function(x) {
  x <- unlist(stri_match_all(x , regex = "(.*)-([0-9]*)"))
  y <- as.numeric(x[3])
  x <- unlist(strsplit(x[2], "-"))
  x <- cipheR::caesar(x[-length(x)], n = y, preset = "lowercase")
  return(paste(x, collapse = " "))
}) |>
  unlist()

as.numeric(stri_extract(dt[tmp][which(x == "northpole object")], 
                        regex = "([0-9]{3})"))
[1] 482