library(tidyverse)
Day 4
Advent of Code: Worked Solutions
Setup
Import libraries:
Read text input from file:
<- read_lines("../input/day04.txt") input
Convert plain text lines into a character matrix:
<- input |>
mtx map(~ matrix(str_split_1(.x, ""), nrow = 1)) |>
do.call(what = rbind)
Part 1
Extract rows and columns as separate text strings from the matrix:
<- apply(mtx, 1, str_flatten)
mtx_rows <- apply(mtx, 2, str_flatten) mtx_cols
Extract diagonals from the matrix by padding each row with leading/trailing spaces, then extracting the new columns as strings:
<- str_dup(" ", 1:nrow(mtx))
padding
<- map(c(I, rev), \(f) {
mtx_diag str_c(padding, f(mtx_rows), rev(padding)) |>
str_split("") |>
list_transpose() |>
map_chr(str_flatten) |>
str_remove_all("\\s")
|>
}) unlist()
Search for the string XMAS
(or its reverse, SAMX
) in each dimension of the matrix and count the total occurrences:
map(c("XMAS", "SAMX"), ~ str_count(c(mtx_rows, mtx_cols, mtx_diag), .x)) |>
unlist() |>
sum()
Part 2
Define the four possible XMAS patterns in a 3x3 grid as a regex string:
<- "M.S.A.M.S"
xmas1 <- "S.M.A.S.M"
xmas4 <- "S.S.A.M.M"
xmas2 <- "M.M.A.S.S"
xmas3 <- str_glue("{xmas1}|{xmas2}|{xmas3}|{xmas4}") xmas_regex
Extract every 3x3 submatrix in the input text block as a text string (concatenating row-wise):
<- expand_grid(row = 3:nrow(mtx), col = 3:ncol(mtx)) |>
sub_mtx pmap(\(row, col) mtx[row - 0:2, col - 0:2]) |>
map_chr(str_flatten)
Count all text strings with a valid XMAS
pattern:
sum(str_detect(sub_mtx, xmas_regex))