Day 4

Advent of Code: Worked Solutions

About
Date

December 4, 2024

Setup

Import libraries:

library(tidyverse)

Read text input from file:

input <- read_lines("../input/day04.txt")

Convert plain text lines into a character matrix:

mtx <- input |> 
  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:

mtx_rows <- apply(mtx, 1, str_flatten)
mtx_cols <- apply(mtx, 2, str_flatten)

Extract diagonals from the matrix by padding each row with leading/trailing spaces, then extracting the new columns as strings:

padding <- str_dup(" ", 1:nrow(mtx))

mtx_diag <- map(c(I, rev), \(f) {
  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:

xmas1 <- "M.S.A.M.S"
xmas4 <- "S.M.A.S.M"
xmas2 <- "S.S.A.M.M"
xmas3 <- "M.M.A.S.S"
xmas_regex <- str_glue("{xmas1}|{xmas2}|{xmas3}|{xmas4}")

Extract every 3x3 submatrix in the input text block as a text string (concatenating row-wise):

sub_mtx <- expand_grid(row = 3:nrow(mtx), col = 3:ncol(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))