Day 3

Advent of Code: Worked Solutions

About
Date

December 3, 2024

Setup

# Libraries
library(tidyverse)

# Read input from file
input <- read_lines("../input/day03.txt") |> 
  str_c(collapse = "")

Part 1

uncorrupt <- function(str) {
  
  str |> 
    
    # Extract all text of the format `mul(a,b)` where a, b are valid integers
    str_extract_all("mul\\(\\d+,\\d+\\)") |> 
    unlist() |> 
    
    # Extract both integers from the mul sequences and multiply them together
    str_extract_all("\\d+") |> 
    map(parse_number) |> 
    map(reduce, prod) |> 
    
    # Sum up the total of all results
    reduce(sum)
  
}

uncorrupt(input)
[1] 178538786

Part 2

# Remove all text between `don't()` and `do()`, then uncorrupt the result
input |> 
  str_remove_all("don't\\(\\).*?do\\(\\)") |>   
  uncorrupt()
[1] 102467299