library(tidyverse)
library(unglue)
Day 3
Advent of Code: Worked Solutions
Setup
Import libraries:
Read text input from file and combine into a single string:
<- read_lines("../input/day03.txt") |>
input str_c(collapse = "")
Part 1
Define a function that “uncorrupts” a string of text by extracting all valid mul
instructions, executing them, and adding them together. We perform this extraction with regex:
<- function(str) {
uncorrupt |>
str str_extract_all("mul\\(\\d+,\\d+\\)") |>
unlist() |>
unglue_data("mul({d1},{d2})", convert = TRUE) |>
pmap_dbl(prod) |>
sum()
}
Run the uncorrupt
function on the puzzle input:
uncorrupt(input)
Part 2
Remove all text between don't()
and do()
, then uncorrupt the result. We use the regex expression .*?
to remove as little text as possible between the don't
and do
statements (ungreedy), so that only the most recent command is used:
|>
input str_remove_all("don't\\(\\).*?do\\(\\)") |>
uncorrupt()