Skip to content

Instantly share code, notes, and snippets.

@ursulams
Created December 5, 2024 07:04
Show Gist options
  • Save ursulams/4ca9d919e04aa5bdcc597e3a1a9170fe to your computer and use it in GitHub Desktop.
Save ursulams/4ca9d919e04aa5bdcc597e3a1a9170fe to your computer and use it in GitHub Desktop.
2024 advent of code day 4
# first star
input <- as.matrix(read.fwf("input.txt", widths = rep(1, 140)))
finder <- function(x) {x <- paste(x, collapse = "")
lengths(regmatches(x, gregexpr("XMAS", x))) +
lengths(regmatches(x, gregexpr("SAMX", x)))
}
# tally horizontal & vertical matches
h_finds <- apply(input, 1, finder)
v_finds <- apply(input, 2, finder)
# for diagonals index letter matrix by n,m value and split into list elements to search R-L and L-R
idx <- row(input) - col(input)
r_l_diag <- lapply(split(input, idx), function(x) paste(x, collapse = ""))
l_r_diag <- lapply(split(input[nrow(input):1, ], idx), function(x) paste(x, collapse = ""))
r_l_finds <- lapply(r_l_diag, finder)
l_r_finds <- lapply(l_r_diag, finder)
d_finds <- sum(mapply("+", r_l_finds, l_r_finds))
sum(h_finds)+sum(v_finds)+d_finds
# second star
# index As, check for only two Ms and two Ss in diagonal
a <- which(input == input, arr.ind = TRUE)
d <- as.matrix(dist(a, "maximum", diag = TRUE))
# extract neighboring values for each element
# extract where max distance is one
d <- apply(d, 1, function(i) input[i == 1])
names(d) <- input
d <- d[grep("A", names(d))]
# get diagonal neighbors only
neighbors <- lapply(d, `[`, c(1,3,6,8))
neighbors <- lapply(neighbors, function(x) paste(x, collapse = ""))
neighbors <- neighbors[grep("MMSS|SMSM|SSMM|MSMS", neighbors)]
length(neighbors)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment