Task 4

Thorn Thaler - <

2021-12-06

1 Setup

1.1 Libraries

library(httr)
library(xml2)
library(magrittr)
library(tibble)
library(dplyr)
library(stringr)
library(purrr)

1.2 Retrieve Data from AoC

session_cookie <- set_cookies(session = keyring::key_get("AoC-GitHub-Cookie"))
base_url <- paste0("https://adventofcode.com/2021/day/", params$task_nr)
puzzle <- GET(base_url,
              session_cookie) %>% 
   content(encoding = "UTF-8") %>% 
   xml_find_all("///article") %>% 
   lapply(as.character)

puzzle_data <- GET(paste0(base_url, "/input"),
                   session_cookie) %>% 
   content(encoding = "UTF-8") %>% 
   strsplit("\n") %>% 
   `[[`(1)

read_boards <- function(stream) {
   markers <- vapply(stream, nchar, integer(1))
   idx <- which(markers == 0L)
   idx <- matrix(c(head(idx, -1), tail(idx, -1)), ncol = 2) %>% 
      `colnames<-`(c("from", "to"))
   apply(idx, 1, function(ii) {
      tab <- stream[seq(ii[["from"]] + 1L, ii[["to"]] - 1L)] %>% 
         paste(collapse = "\n") %>% 
         trimws() %>% 
         read.table(text = .) %>% 
         as.matrix() %>% 
         `colnames<-`(NULL)
   }, simplify = FALSE)
}

puzzle_data <- list(draw = puzzle_data[1] %>% 
                       strsplit(",") %>% 
                       `[[`(1) %>% 
                       as.numeric(),
                    boards = read_boards(puzzle_data))

2 Puzzle Day 4

2.1 Part 1

2.1.1 Description

— Day 4: Giant Squid —

You’re already almost 1.5km (almost a mile) below the surface of the ocean, already so deep that you can’t see any sunlight. What you can see, however, is a giant squid that has attached itself to the outside of your submarine.

Maybe it wants to play bingo?

Bingo is played on a set of boards each consisting of a 5x5 grid of numbers. Numbers are chosen at random, and the chosen number is marked on all boards on which it appears. (Numbers may not appear on all boards.) If all numbers in any row or any column of a board are marked, that board wins. (Diagonals don’t count.)

The submarine has a bingo subsystem to help passengers (currently, you and the giant squid) pass the time. It automatically generates a random order in which to draw numbers and a random set of boards (your puzzle input). For example:

7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1

22 13 17 11  0
 8  2 23  4 24
21  9 14 16  7
 6 10  3 18  5
 1 12 20 15 19

 3 15  0  2 22
 9 18 13 17  5
19  8  7 25 23
20 11 10 24  4
14 21 16 12  6

14 21 17 24  4
10 16 15  9 19
18  8 23 26 20
22 11 13  6  5
 2  0 12  3  7

After the first five numbers are drawn (7, 4, 9, 5, and 11), there are no winners, but the boards are marked as follows (shown here adjacent to each other to save space):

22 13 17 11  0         3 15  0  2 22        14 21 17 24  4
 8  2 23  4 24         9 18 13 17  5        10 16 15  9 19
21  9 14 16  7        19  8  7 25 23        18  8 23 26 20
 6 10  3 18  5        20 11 10 24  4        22 11 13  6  5
 1 12 20 15 19        14 21 16 12  6         2  0 12  3  7

After the next six numbers are drawn (17, 23, 2, 0, 14, and 21), there are still no winners:

22 13 17 11  0         3 15  0  2 22        14 21 17 24  4
 8  2 23  4 24         9 18 13 17  5        10 16 15  9 19
21  9 14 16  7        19  8  7 25 23        18  8 23 26 20
 6 10  3 18  5        20 11 10 24  4        22 11 13  6  5
 1 12 20 15 19        14 21 16 12  6         2  0 12  3  7

Finally, 24 is drawn:

22 13 17 11  0         3 15  0  2 22        14 21 17 24  4
 8  2 23  4 24         9 18 13 17  5        10 16 15  9 19
21  9 14 16  7        19  8  7 25 23        18  8 23 26 20
 6 10  3 18  5        20 11 10 24  4        22 11 13  6  5
 1 12 20 15 19        14 21 16 12  6         2  0 12  3  7

At this point, the third board wins because it has at least one complete row or column of marked numbers (in this case, the entire top row is marked: 14 21 17 24 4).

The score of the winning board can now be calculated. Start by finding the sum of all unmarked numbers on that board; in this case, the sum is 188. Then, multiply that sum by the number that was just called when the board won, 24, to get the final score, 188 * 24 = 4512.

To guarantee victory against the giant squid, figure out which board will win first. What will your final score be if you choose that board?

2.1.2 Solution

The most challenging part about this puzzle was to bring the data into the right format. Once we have a vector of draws and a list of boards we can loop over the draws, mark all matches as TRUE and calculate [row|col]Sums. If either matches the number of rows (cols) we have a BINGO. We use again purrr:reduce instead of an old-fashioned for loop just for the fun of it.

The binary function takes the following relevant arguments1: * matches a list of length 5 lists. The first element corresponds to the board. The second element is a logical matrix showing the matches. The third element is a logical flagging a bingo. The forth element is the last number drawn. The last number is the round whihc we are in. * draw a numeric given the next number.

play_bingo <- function(rounds, draw, 
                       boards = puzzle_data$boards, 
                       stop_on_first = TRUE) {
   bingo_found <- FALSE
   res <- map(rounds, function(round) {
      bingo <- round$bingo
      if (!bingo) {
         res <- round$matches | round$board == draw 
         if (any(rowSums(res) == nrow(round$board),
                 colSums(res) == ncol(round$board))) {
            bingo <- TRUE
            bingo_found <<- TRUE
         }
         list(board = round$board, matches = res, bingo = bingo, draw = draw,
              round = round$round + 1)
      } else {
         round
      }
   })
   all_bingos <- all(map_lgl(res, ~ .x$bingo))
   if (bingo_found & stop_on_first | all_bingos) {
      done(res)
   } else {
      res
   }
}

init <- map(puzzle_data$boards, ~ list(board = .x,
                                       matches = matrix(FALSE, nrow(.x), ncol(.x)),
                                       bingo = FALSE,
                                       draw = NA, round = 0))

bingo_game <- reduce(puzzle_data$draw, play_bingo, 
                     .init = init)


winner <- Filter(\(l) l$bingo, bingo_game)
map_dbl(winner, ~ sum(.x$board[!.x$matches]) * .x$draw)
## [1] 27027

2.2 Part 2

2.2.1 Description

— Part Two —

On the other hand, it might be wise to try a different strategy: let the giant squid win.

You aren’t sure how many bingo boards a giant squid could play at once, so rather than waste time counting its arms, the safe thing to do is to figure out which board will win last and choose that one. That way, no matter which boards it picks, it will win for sure.

In the above example, the second board is the last to win, which happens after 13 is eventually called and its middle column is completely marked. If you were to keep playing until this point, the second board would have a sum of unmarked numbers equal to 148 for a final score of 148 * 13 = 1924.

Figure out which board will win last. Once it wins, what would its final score be?

2.2.2 Solution

We can reuse the previous code, but instead of exiting pre-maturely on first BINGO, we play until all boards have a bingo.

bingo_game <- reduce(puzzle_data$draw, play_bingo, 
                     stop_on_first = FALSE, .init = init)

max_round <- map_dbl(bingo_game, ~ .x$round)
winner <- bingo_game[which.max(max_round)]
map_dbl(winner, ~ sum(.x$board[!.x$matches]) * .x$draw)
## [1] 36975

  1. The original boards are passed in as an argument as well though we could simply use it without an explicit argument. But I prefer expliciteness overimpliciteness.↩︎