1 Setup
1.1 Libraries
library(httr)
library(xml2)
library(magrittr)
library(dplyr)
library(purrr)
library(stringr)
1.2 Retrieve Data from AoC
session_cookie <- set_cookies(session = keyring::key_get("AoC-GitHub-Cookie"))
base_url <- paste0("https://adventofcode.com/", params$year, "/day/", params$task_nr)
puzzle <- GET(base_url,
session_cookie) %>%
content(encoding = "UTF-8") %>%
xml_find_all("///article") %>%
lapply(as.character)
parse_puzzle_data <- function(text_block = readClipboard()) {
if (length(text_block) == 1L) {
text_block <- text_block %>%
str_split("\n") %>%
extract2(1L) %>%
keep(nzchar)
}
text_block %>%
str_split(" ")
}
puzzle_data <- local({
GET(paste0(base_url, "/input"),
session_cookie) %>%
content(encoding = "UTF-8") %>%
parse_puzzle_data()
})
2 Puzzle Day 4
2.1 Part 1
2.1.1 Description
— Day 4: High-Entropy Passphrases —
A new system policy has been put in place that requires all accounts to use a passphrase instead of simply a password. A passphrase consists of a series of words (lowercase letters) separated by spaces.
To ensure security, a valid passphrase must contain no duplicate words.
For example:
-
aa bb cc dd eeis valid. -
aa bb cc dd aais not valid - the wordaaappears more than once. -
aa bb cc dd aaais valid -aaandaaacount as different words.
The system’s full passphrase list is available as your puzzle input. How many passphrases are valid?
2.1.2 Solution
We just need to count the passphrases without duplicated passwords.
count_valid <- function(passphrases) {
vapply(passphrases, \(p) !any(duplicated(p)), logical(1L)) %>%
sum()
}
count_valid(puzzle_data)
## [1] 451
2.2 Part 2
2.2.1 Description
— Part Two —
For added security, yet another system policy has been put in place. Now, a valid passphrase must contain no two words that are anagrams of each other - that is, a passphrase is invalid if any word’s letters can be rearranged to form any other word in the passphrase.
For example:
-
abcde fghijis a valid passphrase. -
abcde xyz ecdabis not valid - the letters from the third word can be rearranged to form the first word. -
a ab abc abd abf abjis a valid passphrase, because all letters need to be used when forming another word. -
iiii oiii ooii oooi oooois valid. -
oiii ioii iioi iiiois not valid - any of these words can be rearranged to form any other word.
Under this new system policy, how many passphrases are valid?
2.2.2 Solution
We preprocess the passphrases, such that we bring each password in its canonical form first, that is, we split it into letters, sort them and paste them together. Then, we use the algorithm from part 1.
preprocess_passphrases <- function(passphrases) {
lapply(passphrases, \(p) str_split(p, "") %>% vapply(\(x) paste(sort(x), collapse = ""),
character(1L)))
}
canoncial_passwords <- preprocess_passphrases(puzzle_data)
count_valid(canoncial_passwords)
## [1] 223