Day 4

Advent of Code: Worked Solutions

About
Date

December 4, 2024

Setup

# Libraries
library(tidyverse)

# Read input from file
input <- read_lines("../input/day04.txt")

Part 1

# Convert vector of text to matrix
txt_to_mtx <- function(txt) {
  txt |> 
    str_split("") |> 
    unlist() |> 
    matrix(nrow = length(txt), byrow = TRUE)
}

# Convert matrix to vector of text
mtx_to_txt <- function(mtx) {
  mtx |> 
    t() |> 
    as_tibble() |> 
    as.list() |> 
    map(str_flatten) |> 
    unlist() |> 
    unname()
}

# Transpose a vector of text
transpose_txt <- function(txt) {
  txt |> 
    txt_to_mtx() |> 
    t() |> 
    mtx_to_txt()
}

# Get rows and columns of input as individual text vectors
rows <- input
cols <- transpose_txt(rows)

# Convert diagonals of input as individual text vectors
pad <- map_chr(
  1:length(rows), 
  ~ str_c(rep_len(" ", .x - 1), collapse = "")
)

diag1 <- str_c(pad, rows, rev(pad)) |> 
  transpose_txt()
diag2 <- str_c(rev(pad), rows, pad) |> 
  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
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 <- glue::glue("{xmas1}|{xmas2}|{xmas3}|{xmas4}")

# Convert input into a matrix
mtx <- txt_to_mtx(input)

# 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) {
        mtx[row_start:(row_start + 2), col_start:(col_start + 2)] |> 
          mtx_to_txt() |> 
          str_flatten()
      }
    )
  }
) |> 
  unlist() |> 
  
  # Count the text strings with a valid XMAS pattern
  str_detect(xmas_regex) |> 
  sum()
[1] 1948