Task 10

Thorn Thaler - <

2025-03-07

1 Setup

1.1 Libraries

library(httr)
library(xml2)
library(tibble)
library(magrittr)
library(dplyr)
library(stringr)
library(knitr)
library(purrr)

1.2 Retrieve Data from AoC

session_cookie <- set_cookies(session = keyring::key_get("AoC-GitHub-Cookie"))
base_url <- paste0("https://adventofcode.com/", params$year, "/day/", params$task_nr)
puzzle <- GET(base_url,
              session_cookie) %>% 
  content(encoding = "UTF-8") %>% 
  xml_find_all("///article") %>% 
  lapply(as.character)

parse_puzzle_data <- function(text_block = readClipboard()) {
  if (length(text_block) == 1L) {
    text_block <- text_block %>% 
      str_split("\n") %>% 
      extract2(1L) %>% 
      keep(nzchar)
  }
  text_block %>% 
    str_split("") %>% 
    extract2(1L) %>% 
    as.integer()
}

puzzle_data <- local({
  GET(paste0(base_url, "/input"),
      session_cookie) %>% 
    content(encoding = "UTF-8") %>% 
    parse_puzzle_data()
})

2 Puzzle Day 10

2.1 Part 1

2.1.1 Description

— Day 10: Elves Look, Elves Say —

Today, the Elves are playing a game called look-and-say. They take turns making sequences by reading aloud the previous sequence and using that reading as the next sequence. For example, 211 is read as “one two, two ones”, which becomes 1221 (1 2, 2 1s).

Look-and-say sequences are generated iteratively, using the previous value as input for the next step. For each step, take the previous value, and replace each run of digits (like 111) with the number of digits (3) followed by the digit itself (1).

For example:

  • 1 becomes 11 (1 copy of digit 1).
  • 11 becomes 21 (2 copies of digit 1).
  • 21 becomes 1211 (one 2 followed by one 1).
  • 1211 becomes 111221 (one 1, one 2, and two 1s).
  • 111221 becomes 312211 (three 1s, two 2s, and one 1).

Starting with the digits in your puzzle input, apply this process 40 times. What is the length of the result?

2.1.2 Solution

We can use rle to get the run length encoded version of the input and build the string from there.

look_and_say <- function(code, reps) {
  i <- 1
  while (i <= reps) {
    rl <- rle(code)  
    n <- length(rl$lengths)
    code <- rep(NA_integer_, 2L * n)
    even <- seq(2L, by = 2L, length.out = n)
    code[even] <- rl$values
    code[even - 1L] <- rl$lengths
    i <- i + 1
  }
  length(code)
}

look_and_say(puzzle_data, 40L)
## [1] 492982

2.2 Part 2

2.2.1 Description

— Part Two —

Neat, right? You might also enjoy hearing John Conway talking about this sequence (that’s Conway of Conway’s Game of Life fame).

Now, starting again with the digits in your puzzle input, apply this process 50 times. What is the length of the new result?

2.2.2 Solution

All we need to do is to apply the same function 50 times now.

look_and_say(puzzle_data, 50L)
## [1] 6989950