library(tidyverse)
Day 8
Advent of Code: Worked Solutions
Setup
Import libraries:
Read input from file:
<- read_lines("../input/day08.txt") input
Convert text input to a character matrix:
<- input |>
mtx str_split("") |>
unlist() |>
matrix(nrow = length(input), byrow = TRUE)
Part 1
Define a helper function to check if a coordinate x
is within the bounds of the map (mtx):
<- \(x, map) between(x[1], 1, nrow(map)) & between(x[2], 1, ncol(map)) in_bounds
Define a helper function to compute the antinodes of a given pair of antenna coordinates on a map:
<- function(x1, x2, map) {
antinode_pair <- x2 - x1
diff keep(list(x1 - diff, x2 + diff), ~ in_bounds(.x, map))
}
Define a helper function to get the coordinates of every antenna of a given frequency on a map:
<- function(freq, map) {
get_antennas <- which(map == freq, arr.ind = TRUE)
antennas split(antennas, row(antennas))
}
Define a function to compute all antinodes of a given frequency in a map:
<- function(freq, map, f) {
get_all_antinodes <- get_antennas(freq, map)
antennas
<- combn(antennas, 2)
pairs <- split(pairs, col(pairs))
pairs
|>
pairs map(~ f(.x[[1]], .x[[2]], map)) |>
list_flatten() |>
unique()
}
Compute the distinct set of frequencies in the map:
<- mtx |>
freqs as.vector() |>
unique() |>
keep(~ .x %in% c(letters, LETTERS, as.character(0:9)))
Count all distinct antinode locations across all frequencies in the map:
|>
freqs map(~ get_all_antinodes(.x, mtx, antinode_pair)) |>
list_flatten() |>
unique() |>
length()
Part 2
Update the antinode function which computes the antidotes of a given pair of antennas:
<- function(x1, x2, map) {
antinode_set <- x2 - x1
diff <- list(x1, x2)
antinodes
<- 1
i while(in_bounds(x2 + i * diff, map)) {
<- c(antinodes, list(as.integer(x2 + i * diff)))
antinodes <- i + 1
i
}
<- 1
i while(in_bounds(x1 - i * diff, map)) {
<- c(antinodes, list(as.integer(x1 - i * diff)))
antinodes <- i + 1
i
}
antinodes }
Re-run puzzle input:
|>
freqs map(~ get_all_antinodes(.x, mtx, antinode_set)) |>
list_flatten() |>
unique() |>
length()