# Libraries
library(tidyverse)
library(unglue)
# Read input from file
<- read_lines("../input/day08.txt", skip_empty_rows = TRUE) input
Day 8
Advent of Code: Worked Solutions
Setup
Part 1
Parse input text into sets of left/right instructions and the maps of the node network:
<- input |>
instructions head(1) |>
str_split_1("")
<- input |>
network tail(-1) |>
unglue_data("{node} = ({L}, {R})") |>
nest(LR = c(L, R)) |>
mutate(LR = map(LR, as.list)) |>
deframe()
Starting at the AAA node, advance through the list of instructions until the ZZZ node is reached:
# Initialize
<- length(instructions)
n_rep <- "AAA"
cur_node <- 0
i
repeat {
if (cur_node == "ZZZ") break
<- instructions[i %% n_rep + 1]
cur_dir <- network[[cur_node]][[cur_dir]]
cur_node <- i + 1
i
}
i
[1] 19631
Part 2
For each node ending with ‘A’, compute the number of necessary steps until it reaches a node ending with ‘Z’ and loops.
<- function(node_start) {
steps_to_z
# Initialize
<- node_start
cur_node <- 0
i
repeat {
if (str_ends(cur_node, "Z")) return(i)
<- instructions[i %% n_rep + 1]
cur_dir <- network[[cur_node]][[cur_dir]]
cur_node <- i + 1
i
}
}
<- names(network) |>
cycles keep(~ str_ends(.x, "A")) |>
map_dbl(steps_to_z)
Take the least common multiple of the result:
reduce(cycles, numbers::LCM) |>
format(scientific = FALSE)
[1] "21003205388413"