# Libraries
library(tidyverse)
# Read input from file
<- read_lines("../input/day04.txt") input
Day 4
Advent of Code: Worked Solutions
Setup
Part 1
# Convert vector of text to matrix
<- function(txt) {
txt_to_mtx |>
txt str_split("") |>
unlist() |>
matrix(nrow = length(txt), byrow = TRUE)
}
# Convert matrix to vector of text
<- function(mtx) {
mtx_to_txt |>
mtx t() |>
as_tibble() |>
as.list() |>
map(str_flatten) |>
unlist() |>
unname()
}
# Transpose a vector of text
<- function(txt) {
transpose_txt |>
txt txt_to_mtx() |>
t() |>
mtx_to_txt()
}
# Get rows and columns of input as individual text vectors
<- input
rows <- transpose_txt(rows)
cols
# Convert diagonals of input as individual text vectors
<- map_chr(
pad 1:length(rows),
~ str_c(rep_len(" ", .x - 1), collapse = "")
)
<- str_c(pad, rows, rev(pad)) |>
diag1 transpose_txt()
<- str_c(rev(pad), rows, pad) |>
diag2 transpose_txt()
# Loop over rows, columns, and diagnoals and count occurrences of "XMAS"
map_int(
list(rows, cols, diag1, diag2),
~ sum(str_count(.x, "XMAS") + str_count(.x, "SAMX"))
|>
) sum()
[1] 2599
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 <- glue::glue("{xmas1}|{xmas2}|{xmas3}|{xmas4}")
xmas_regex
# Convert input into a matrix
<- txt_to_mtx(input)
mtx
# Extract every 3x3 submatrix in the input text block as a text string
map(
1:(nrow(mtx) - 2),
function(row_start) {
map_chr(
1:(ncol(mtx) - 2),
function(col_start) {
:(row_start + 2), col_start:(col_start + 2)] |>
mtx[row_startmtx_to_txt() |>
str_flatten()
}
)
}|>
) unlist() |>
# Count the text strings with a valid XMAS pattern
str_detect(xmas_regex) |>
sum()
[1] 1948