Last active
December 4, 2021 16:28
-
-
Save xvrdm/f2192e03643bd7068fead31f0523c3c2 to your computer and use it in GitHub Desktop.
Advent of Code 2021 in R - Day 4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(tidyverse) | |
raw_data <- readr::read_lines("days/d04/data.txt") %>% | |
stringr::str_trim() | |
BOARD_SIZE <- 5 | |
draws <- raw_data[1] %>% | |
stringr::str_split(",") %>% | |
.[[1]] %>% | |
as.numeric() %>% | |
purrr::accumulate(c) | |
boards <- raw_data[2:length(raw_data)] %>% | |
stringr::str_subset("^$", negate = TRUE) %>% | |
split(ceiling(seq_along(.)/BOARD_SIZE)) %>% | |
purrr::map(function(x) { | |
stringr::str_split(x, "[:space:]+", simplify = T) %>% | |
{matrix(as.numeric(.), ncol=ncol(.))} | |
}) | |
is_set_in_draw <- function(x, draw) | |
length(setdiff(x, draw)) == 0 | |
test_board <- function(draw, board) { | |
i <- 1 | |
while(i <= 5) { | |
if (is_set_in_draw(board[i,], draw) | | |
is_set_in_draw(board[,i], draw) ) { | |
return(TRUE) | |
} | |
i <- i + 1 | |
} | |
FALSE | |
} | |
get_score <- function(draw, board) { | |
sum(c(board)[!(c(board) %in% draw)])*draw[length(draw)] | |
} | |
# Challenge 1 | |
b <- boards[[1]] | |
d <- draws[1] | |
for (draw in draws) { | |
tests <- purrr::map_lgl(boards, ~test_board(draw, .)) | |
if (any(tests)) { | |
ib <- which.max(tests) # index of first TRUE board | |
winning_board <- boards[[ib]] | |
winning_draw <- draw | |
break | |
} | |
} | |
get_score(winning_board, winning_draw) | |
# Challenge 2 | |
b <- boards[[1]] | |
d <- draws[1] | |
for (draw in draws) { | |
tests <- purrr::map_lgl(boards, ~test_board(draw, .)) | |
if (all(tests)) { | |
winning_board <- boards[[length(boards)]] | |
winning_draw <- draw | |
break | |
} | |
boards <- boards[!tests] # no need to keep already won boards | |
} | |
get_score(winning_board, winning_draw) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment