library(tidyverse)
library(unglue)
Day 5
Advent of Code: Worked Solutions
Setup
Import libraries:
Read text input from file:
<- read_lines("../input/day05.txt", skip_empty_rows = TRUE) input
Extract the page-ordering rules from the input:
<- input |>
rules unglue_data("{p1}|{p2}", convert = TRUE) |>
drop_na()
Extract the page sequences from the input:
<- input |>
pages discard_at(1:nrow(rules)) |>
str_split(",") |>
map(parse_number)
Part 1
Define a function to sort a given vector of page numbers according to the rules that apply to those page numbers:
<- function(seq) {
sort_by_rules <- rules |>
active_rules filter(p1 %in% seq & p2 %in% seq)
repeat {
<- FALSE
swap_occurred for (i in 1:nrow(active_rules)) {
<- filter(active_rules, row_number() == i)
rule <- which(seq == rule$p1)
idx1 <- which(seq == rule$p2)
idx2
if (idx1 > idx2) {
<- rule$p2
seq[[idx1]] <- rule$p1
seq[[idx2]] <- TRUE
swap_occurred
}
}if (!swap_occurred)
return(seq)
} }
Sort all page sequences in the puzzle input and extract the center page of the result:
<- pages |>
output as_tibble_col(column_name = "update") |>
mutate(
resorted = map(update, sort_by_rules),
is_sorted = map2_lgl(update, resorted, identical),
center_page = map_int(resorted, ~ .x[(length(.x) + 1) / 2])
)
For all properly-ordered updates, sum the center page numbers:
|>
output filter(is_sorted) |>
pull(center_page) |>
sum()
Part 2
For all improperly-ordered updates, sum their sorted center pages
|>
output filter(!is_sorted) |>
pull(center_page) |>
sum()