Created
December 17, 2020 16:11
-
-
Save klmr/566fb39889e333d3d848c1cedc988dc4 to your computer and use it in GitHub Desktop.
Advent of Code day 15 in R
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
test_cases_desc = R'( | |
Given the starting numbers 1,3,2, the 2020th number spoken is 1. | |
Given the starting numbers 2,1,3, the 2020th number spoken is 10. | |
Given the starting numbers 1,2,3, the 2020th number spoken is 27. | |
Given the starting numbers 2,3,1, the 2020th number spoken is 78. | |
Given the starting numbers 3,2,1, the 2020th number spoken is 438. | |
Given the starting numbers 3,1,2, the 2020th number spoken is 1836. | |
)' | |
`%>%` = magrittr::`%>%` | |
test_cases = stringr::str_match_all( | |
test_cases_desc, | |
'Given the starting numbers ([^ ]*), the 2020th number spoken is ([^.]*)' | |
) %>% | |
.[[1L]] %>% | |
.[, -1L] %>% | |
{list( | |
Start = lapply(strsplit(.[, 1L], ','), as.integer), | |
Result = as.integer(.[, 2L]) | |
)} %>% | |
purrr::transpose() | |
################################################################### | |
inc = function (var) { | |
var = deparse(substitute(var)) | |
old = get(var, envir = parent.frame()) | |
assign(var, old + 1L, envir = parent.frame()) | |
invisible(old) | |
} | |
dict = function (...) { | |
structure(list2env(list(...)), class = 'dict') | |
} | |
`[[.dict` = function (dict, key) { | |
key = as.character(key) | |
NextMethod() | |
} | |
`[[<-.dict` = function (dict, key, value) { | |
key = as.character(key) | |
NextMethod() | |
} | |
play_game = function (start, until = 2020L, verbose = FALSE) { | |
log = function (msg) if (verbose) message(glue::glue(msg)) | |
seen = dict() | |
turn = 1L | |
for (num in start) { | |
log('{turn}: {num}') | |
last_seen = seen[[num]] | |
seen[[num]] = inc(turn) | |
} | |
while (turn <= until) { | |
num = if (is.null(last_seen)) 0L else turn - last_seen - 1L | |
log('{turn}: {num}') | |
last_seen = seen[[num]] | |
seen[[num]] = inc(turn) | |
} | |
num | |
} | |
play_game(c(0L, 3L, 6L), until = 10L, verbose = TRUE) | |
stopifnot(play_game(c(0L, 3L, 6L), until = 2020L) == 436L) | |
for (test in test_cases) local({ | |
result = play_game(test$Start) | |
if (result != test$Result) { | |
message(glue::glue('Failed test: play_game({test$Start}) = {result}, expected {test$Result}')) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment