# Libraries
library(tidyverse)
# Read input from file
<- read_lines("../input/day13.txt", skip_empty_rows = FALSE) input
Day 13
Advent of Code: Worked Solutions
Setup
Part 1
Convert each set of input strings into its own matrix:
<- tibble(chr = input) |>
mtx group_split(cumsum(chr == "")) |>
map(~ pull(.x, chr)) |>
map(
~ str_split(.x, "") |>
unlist() |>
matrix(nrow = sum(.x != ""), byrow = TRUE)
)
Define a function that checks for a mirror along the given dimension (rows vs columns) of a given matrix:
<- function(mtx, dim = c("row", "col")) {
mirror_idx <- split(mtx, get(case_match(dim, "row" ~ "col", "col" ~ "row"))(mtx))
vecs <- get(str_c("n", dim))(mtx)
len
<- c(0)
refl_idx
for (idx in 1:(len - 1)) {
<- min(idx, len - idx)
n_trim
<- vecs |>
is_mirror map_lgl(\(vec) {
<- rev(vec[1:idx])[1:n_trim]
h1 <- vec[(idx + 1):(idx + n_trim)]
h2 all(h1 == h2)
|>
}) all()
if (is_mirror)
<- c(refl_idx, idx)
refl_idx
}
refl_idx }
For each matrix in the list, add the column indices of each vertical reflection line with 100 times the row indices of each horizontal reflection line:
<- function(mtx_list) {
score_matrices |>
mtx_list map_dbl(~ sum(mirror_idx(.x, "col")) + sum(mirror_idx(.x, "row") * 100)) |>
sum()
}
score_matrices(mtx)
[1] 30575
Part 2
Define a function that finds the row or column index of the single smudge for a given matrix:
<- function(mtx, dim = c("row", "col")) {
smudge_idx
<- split(mtx, get(case_match(dim, "row" ~ "col", "col" ~ "row"))(mtx))
vecs <- get(str_c("n", dim))(mtx)
len
for (idx in 1:(len - 1)) {
<- min(idx, len - idx)
n_trim
<- vecs |>
noteq map(\(vec) {
<- rev(vec[1:idx])[1:n_trim]
h1 <- vec[(idx + 1):(idx + n_trim)]
h2 which(h1 != h2)
})
if (length(unlist(noteq)) == 1) return(idx)
}return(0)
}
Re-score the input:
<- function(mtx_list) {
score_unsmudged |>
mtx_list map_dbl(~ sum(smudge_idx(.x, "col")) + sum(smudge_idx(.x, "row") * 100)) |>
sum()
}
score_unsmudged(mtx)
[1] 37478