AdventOfCode > 2026
input_year <- 2026
input_day <- 4
source(here::here("R/adventofcode.R"))
adventofcode_load()
input <- adventofcode_input(input_year, input_day, what = "character")
example <- "rgbrgbrgbr
?rv
o??v???y
??bg?v??
??b?????
???"
barcodes <- example |>
str_split_1("\n")
colors <- c("r", "o", "y", "g", "b", "v")
can_generate_barcode <- \(instructions, barcode) {
instructions <- str_split_1(instructions, "")
barcode <- str_split_1(barcode, "")
if (length(instructions) == 0L || any(!instructions %in% colors)) {
return(FALSE)
}
printed <- rep(instructions, length.out = length(barcode))
all(barcode == "?" | barcode == printed)
}
can_generate_barcode("rgbrgbrgbr", barcodes[[1]])
## [1] TRUE
can_generate_barcode("rgb", barcodes[[1]])
## [1] TRUE
can_generate_barcode("rrv", barcodes[[2]])
## [1] TRUE
can_generate_barcode("vr", barcodes[[2]])
## [1] TRUE
can_generate_barcode("ovvvyyyy", barcodes[[3]])
## [1] TRUE
generate_instructions <- \(size) {
combinations <- expand.grid(
rep(list(colors), size),
KEEP.OUT.ATTRS = FALSE,
stringsAsFactors = FALSE
)
do.call(paste0, as.list(combinations))
}
combinations <- lapply(seq_len(7L), generate_instructions)
combinations[[2L]]
## [1] "rr" "or" "yr" "gr" "br" "vr" "ro" "oo" "yo" "go" "bo" "vo" "ry" "oy" "yy"
## [16] "gy" "by" "vy" "rg" "og" "yg" "gg" "bg" "vg" "rb" "ob" "yb" "gb" "bb" "vb"
## [31] "rv" "ov" "yv" "gv" "bv" "vv"
barcode <- barcodes[[1]]
N <- nchar(barcode)
i <- 1
while (i < N) {
if (
any(map_lgl(combinations[[i]], \(x) {
can_generate_barcode(x, barcode)
}))
) {
break
}
i <- i + 1
}
print(i)
## [1] 3
filter_candidates <- \(candidates, barcode) {
if (length(candidates) == 0L) {
return(candidates)
}
barcode_chars <- str_split_1(barcode, "")
readable_positions <- which(barcode_chars != "?")
instruction_length <- nchar(candidates[[1L]])
for (position in readable_positions) {
instruction_slot <- (position - 1L) %% instruction_length + 1L
colors_at_slot <- substr(candidates, instruction_slot, instruction_slot)
candidates <- candidates[colors_at_slot == barcode_chars[position]]
if (length(candidates) == 0L) break
}
candidates
}
produce_shortest_sequence <- \(barcode) {
N <- nchar(barcode)
i <- 1L
while (i < N) {
candidates <- filter_candidates(combinations[[i]], barcode)
if (purrr::some(candidates, \(x) can_generate_barcode(x, barcode))) {
return(i)
}
i <- i + 1L
}
return(i)
}
produce_shortest_sequence(barcodes[[3]])
## [1] 5
example <- "rgbrgbrgbr
?rv
o??v???y
??bg?v??
??b?????
???"
compute1 <- \(x) {
x |>
str_split_1("\n") |>
trimws() |>
discard(\(barcode) barcode == "") |>
map_int(produce_shortest_sequence, .progress = TRUE) |>
sum()
}
result <- compute1(example)
result
## [1] 16
assertthat::are_equal(16, result)
## [1] TRUE
result_part1 <- input |>
compute1()
result_part1
## [1] 8221
Since I did brute force + filtering for part 1, I don’t feel like solving part 2 today :)