library(tidyverse)
Day 25
Advent of Code: Worked Solutions
Setup
Import libraries:
Read and parse text input from file:
<- read_lines("../input/day25.txt") input
Part 1
Convert input to a matrix. Represent N/S-facing values as imaginary numbers and W/E-facing values as real numbers.
<- input |>
mtx str_split("") |>
reduce(rbind) |>
unname()
<- nrow(mtx)
h <- ncol(mtx) w
Define functions to check if the value ahead of the current one to the south or east are blocked:
<- \(x) unname(rbind(tail(x, -1), head(x, 1))) != "."
is_blocked_s <- \(x) t(is_blocked_s(t(x))) is_blocked_e
Define functions to shift the matrix values to the south or east
<- function(mtx) {
move_s <- is_blocked_s(mtx)
blocked <- mtx == "v"
active
<- which(active & !blocked, arr.ind = TRUE)
old_pos
<- old_pos
new_pos "row"] <- (new_pos[, "row"] %% h) + 1
new_pos[,
<- "v"
mtx[new_pos] <- "."
mtx[old_pos]
mtx
}
<- function(mtx) {
move_e <- is_blocked_e(mtx)
blocked <- mtx == ">"
active
<- which(active & !blocked, arr.ind = TRUE)
old_pos
<- old_pos
new_pos "col"] <- (new_pos[, "col"] %% w) + 1
new_pos[,
<- ">"
mtx[new_pos] <- "."
mtx[old_pos]
mtx
}
<- \(x) move_s(move_e(x)) move
Loop until we don’t see any difference between the previous and current steps:
<- function(mtx) {
n_steps <- 1
n <- mtx
prv
repeat {
<- move(prv)
cur
if (all(cur == prv))
return(n)
<- cur
prv <- n + 1
n
}
}
n_steps(mtx)