Created
December 4, 2024 06:33
-
-
Save ursulams/2fa78d99e5a1b2b7b86202d3f2809a76 to your computer and use it in GitHub Desktop.
2024 advent of code day 3
This file contains hidden or 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
# first star | |
input <- paste0(readLines("input.txt"), collapse = " ") # ingest as one big blob | |
expression <- "mul\\([0-9]+,[0-9]+\\)" | |
# returns parsed string with generic function to allow for string to expression conversion | |
renamer <- function(x){ | |
str2lang(gsub("mul", "prod", regmatches(x, gregexpr(expression, x)))) | |
} | |
multipliers <- renamer(input) | |
products <- sapply(multipliers, function(x) eval(parse(text = x))) | |
do.call(sum, products[-1]) | |
# second star | |
enabled_input <- gsub("don't\\(\\).*?(?=do\\(\\))", "\\1", input, perl = TRUE) | |
enabled_multipliers <- renamer(enabled_input) | |
enabled_products <- sapply(enabled_multipliers, function(x) eval(parse(text = x))) | |
do.call(sum, enabled_products[-1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment