Day 11

Advent of Code: Worked Solutions

About
Date

December 11, 2024

Setup

Import libraries:

library(tidyverse)

Disable scientific formatting when displaying large numbers:

options(scipen = 999)

Read input from file into a numeric vector:

input <- scan("../input/day11.txt")

Part 1

Define a function for a single blink. If x is zero, it becomes 1. If x has an even number of digits, the value is split. If odd, it’s multiplied by 2024.

blink <- function(x) {
  char <- format(x, scientific = FALSE)
  n <- str_length(char)
  
  if (x == 0) 
    1
  else if (n %% 2 == 0)
    parse_number(c(str_sub(char, 1, n / 2), str_sub(char, n / 2 + 1, n)))
  else 
    x * 2024
}

Define a recursive function to blink n times. We don’t store each stone separately – instead, we store the current unique stones and their counts at every step:

blink_n <- function(df, n) {
  if (n == 0)
    return(sum(df$n))
  
  df |> 
    mutate(stones = map(stones, blink)) |> 
    unnest(stones) |> 
    summarize(n = sum(n), .by = stones) |> 
    blink_n(n - 1)
}

Run the blink function 25 times on the puzzle input, starting each stone with a count of 1:

blink_n(tibble(stones = input, n = 1), 25)

Part 2

Run blink function 75 times on puzzle input:

blink_n(tibble(stones = input, n = 1), 75)