Advent of Code 2023 - Day 4Scratchcards

R | Problem statement | Source code | Tags:

Part 1

The score for each line is just the number of numbers that are in winning.

num_matches <- function(line) {
winning <- line$winning
numbers <- line$numbers
length(numbers[numbers %in% winning])
}
R

Because no match = 0, 1 match = 1 = 202^0, nn matches = 2n12^{n-1}, the score can be calculated as 2num_matches(line)1\lfloor 2^{num\_matches(line) - 1}\rfloor (floor is needed because 201=0.52^{0-1} = 0.5).

scores <- sapply(lines, num_matches)
scores <- floor(2^(scores - 1))
cat(sum(scores), "\n")
R

Part 2

We can do bin counting of each scratchcard. Each card increments the nn cards following it by its own count.

counts <- rep(1, length(lines))
for (i in seq_along(scores)) {
if (scores[i] > 0) {
for (j in (i + 1):(i + scores[i])) {
counts[j] <- counts[j] + counts[i]
}
}
}
cat(sum(counts), "\n")
R