library(tidyverse)
input <- read_csv(file = "inputs/2016/04.txt", col_names = "original")Day 4: Security Through Obscurity
Part One
chesum_eval <- function(x) {
letters <- x |>
str_split_1(pattern = "") |>
table() |>
sort(decreasing = TRUE) |>
names() |>
_[1:5] |>
paste0(collapse = "")
}
real_rooms <- input |>
mutate(sector_id = as.numeric(str_extract(string = original, pattern = "[0-9]+")),
checksum = str_extract(string = original, pattern = "(?<=\\[)[a-z]*"),
encrypted_name = str_extract(string = original, pattern = "[a-z\\-]*(?=-\\d+)"),
encrypted_name = str_remove_all(string = encrypted_name, pattern = "\\-"),
chesum_eval = map_chr(.x = encrypted_name, .f = chesum_eval),
real_room = checksum == chesum_eval)
real_rooms |>
filter(real_room == TRUE) |>
summarise(total = sum(sector_id)) |>
pull(total) |>
cat()
## 185371Part Two
room_names <- input |>
mutate(sector_id = as.numeric(str_extract(string = original, pattern = "[0-9]+")),
encrypted = str_remove(string = original, pattern = "-[0-9]+\\[[a-z]+\\]"))
decrypt <- function(string, sector_id) {
decrypted <- character(0)
for (element in str_split_1(string = string, pattern = "")) {
if (element == "-")
decrypted <- c(decrypted, " ")
else {
index <- (which(letters == element) + sector_id) %% 26
decrypted <- c(decrypted, letters[index])
}
}
return(paste(decrypted, collapse = ""))
}
room_names <- room_names |>
mutate(decrypted = map2_chr(.x = encrypted, .y = sector_id, .f = decrypt))
room_names |>
filter(decrypted == "northpole object storage") |>
pull(sector_id) |>
cat()
## 984room_names |>
rowid_to_column("row_number") |>
filter(decrypted == "northpole object storage") |>
pull("row_number") |>
cat()
## 476