Skip to content

Instantly share code, notes, and snippets.

@mathesong
Created December 3, 2024 06:35
Show Gist options
  • Save mathesong/352e6cb75bc17ede920eaf8da25c0152 to your computer and use it in GitHub Desktop.
Save mathesong/352e6cb75bc17ede920eaf8da25c0152 to your computer and use it in GitHub Desktop.
Advent of Code 2024: Day 3
library(tidyverse)
input <- readLines("input")
##### Part 1 #####
vals <- tibble(
mul = str_match_all(paste(input, collapse = ""),
"(mul\\(\\d{1,3},\\d{1,3}\\))")[[1]][,2]) %>%
mutate(val1 = as.numeric(str_match(mul, "\\((\\d{1,3})\\,")[,2]),
val2 = as.numeric(str_match(mul, "\\,(\\d{1,3})\\)")[,2])) %>%
mutate(product = val1*val2)
sum(vals$product)
##### Part 2 #####
vals <- vals %>%
mutate(start = str_locate_all(paste(input, collapse = ""),
"mul\\(\\d{1,3},\\d{1,3}\\)")[[1]][,1])
cond_true <- tibble(
start = str_locate_all(paste(input, collapse = ""),
"do\\(\\)")[[1]][,1] )
cond_false <- tibble(
start = str_locate_all(paste(input, collapse = ""),
"don\\'t\\(\\)")[[1]][,1] )
cond <- bind_rows(cond_true %>% mutate(condition = TRUE),
cond_false %>% mutate(condition = FALSE))
vals_cond <- full_join(vals, cond) %>%
arrange(start) %>%
mutate(n = 1:n()) %>%
mutate(condition = ifelse(n == 1, TRUE, condition)) %>%
fill(condition) %>%
filter(condition) %>%
filter(!is.na(product))
sum(vals_cond$product)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment