Task 12

Thorn Thaler - <

2025-10-09

1 Setup

1.1 Libraries

library(httr)
library(xml2)
library(magrittr)
library(dplyr)
library(purrr)
library(stringr)
library(bit64)
library(digest)

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)
  }
  start <- text_block[[1L]] %>% 
    str_extract("[.#]+") %>% 
    unlist()
  rules <- text_block %>% 
    str_detect(fixed("=>"))
  rules <- text_block[rules] %>% 
    str_split(fixed(" => ")) %>% 
    map(~ set_names(.x[2L], .x[1L])) %>% 
    flatten_chr()
  
  list(start = start, rules = rules)
               
}

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

2 Puzzle Day 12

2.1 Part 1

2.1.1 Description

— Day 12: Subterranean Sustainability —

The year 518 is significantly more underground than your history books implied. Either that, or you’ve arrived in a vast cavern network under the North Pole.

After exploring a little, you discover a long tunnel that contains a row of small pots as far as you can see to your left and right. A few of them contain plants - someone is trying to grow things in these geothermally-heated caves.

The pots are numbered, with 0 in front of you. To the left, the pots are numbered -1, -2, -3, and so on; to the right, 1, 2, 3…. Your puzzle input contains a list of pots from 0 to the right and whether they do (#) or do not (.) currently contain a plant, the initial state. (No other pots currently contain plants.) For example, an initial state of #..##…. indicates that pots 0, 3, and 4 currently contain plants.

Your puzzle input also contains some notes you find on a nearby table: someone has been trying to figure out how these plants spread to nearby pots. Based on the notes, for each generation of plants, a given pot has or does not have a plant based on whether that pot (and the two pots on either side of it) had a plant in the last generation. These are written as LLCRR => N, where L are pots to the left, C is the current pot being considered, R are the pots to the right, and N is whether the current pot will have a plant in the next generation. For example:

  • A note like ..#.. => . means that a pot that contains a plant but with no plants within two pots of it will not have a plant in it during the next generation.
  • A note like ##.## => . means that an empty pot with two plants on each side of it will remain empty in the next generation.
  • A note like .##.# => # means that a pot has a plant in a given generation if, in the previous generation, there were plants in that pot, the one immediately to the left, and the one two pots to the right, but not in the ones immediately to the right and two to the left.

It’s not clear what these plants are for, but you’re sure it’s important, so you’d like to make sure the current configuration of plants is sustainable by determining what will happen after 20 generations.

For example, given the following input:

initial state: #..#.#..##......###...###

...## => #
..#.. => #
.#... => #
.#.#. => #
.#.## => #
.##.. => #
.#### => #
#.#.# => #
#.### => #
##.#. => #
##.## => #
###.. => #
###.# => #
####. => #

For brevity, in this example, only the combinations which do produce a plant are listed. (Your input includes all possible combinations.) Then, the next 20 generations will look like this:

                 1         2         3     
       0         0         0         0     
 0: ...#..#.#..##......###...###...........
 1: ...#...#....#.....#..#..#..#...........
 2: ...##..##...##....#..#..#..##..........
 3: ..#.#...#..#.#....#..#..#...#..........
 4: ...#.#..#...#.#...#..#..##..##.........
 5: ....#...##...#.#..#..#...#...#.........
 6: ....##.#.#....#...#..##..##..##........
 7: ...#..###.#...##..#...#...#...#........
 8: ...#....##.#.#.#..##..##..##..##.......
 9: ...##..#..#####....#...#...#...#.......
10: ..#.#..#...#.##....##..##..##..##......
11: ...#...##...#.#...#.#...#...#...#......
12: ...##.#.#....#.#...#.#..##..##..##.....
13: ..#..###.#....#.#...#....#...#...#.....
14: ..#....##.#....#.#..##...##..##..##....
15: ..##..#..#.#....#....#..#.#...#...#....
16: .#.#..#...#.#...##...#...#.#..##..##...
17: ..#...##...#.#.#.#...##...#....#...#...
18: ..##.#.#....#####.#.#.#...##...##..##..
19: .#..###.#..#.#.#######.#.#.#..#.#...#..
20: .#....##....#####...#######....#.#..##.

The generation is shown along the left, where 0 is the initial state. The pot numbers are shown along the top, where 0 labels the center pot, negative-numbered pots extend to the left, and positive pots extend toward the right. Remember, the initial state begins at pot 0, which is not the leftmost pot used in this example.

After one generation, only seven plants remain. The one in pot 0 matched the rule looking for ..#.., the one in pot 4 matched the rule looking for .#.#., pot 9 matched .##.., and so on.

In this example, after 20 generations, the pots shown as # contain plants, the furthest left of which is pot -2, and the furthest right of which is pot 34. Adding up all the numbers of plant-containing pots after the 20th generation produces 325.

After 20 generations, what is the sum of the numbers of all pots which contain a plant?

2.1.2 Solution

The first part is rather straight forward. We just have to keep track of the position and decide to remove leading and trailing dots as rule number 2 states that an empty quintuple produces an empty pot ..... => . (otherwise the puzzle would not be solvable). In each iteration we potentially add 2 new plants to the generation at the beginning, hence we need to decrease the offset by 2. However, for each . we remove from the beginning, we increase the offset again by 1 as we are deliberately ignoring this empty pot.

grow_plants <- function(n, start = puzzle_data$start, rules = puzzle_data$rules) {
  offset <- 0
  for (i in seq_len(n)) {
    offset <- offset - 2
    start <- paste0("....", start, "....")
    new_gen <- ""
    for (j in 3:(nchar(start) - 2L)) {
      token <- str_sub(start, j - 2, j + 2L)
      if (!token %in% names(rules)) {
        new_gen <- paste0(new_gen, ".")
      } else {
        new_gen <- paste0(new_gen, rules[token])
      }
    }
    ## remove dots at the end
    start <- str_remove(new_gen, "\\.*$") %>% 
      extract2(1L)
    ## get number of dots in the beginning
    head <- str_extract(start, "^\\.*") %>% 
      extract2(1L)
    start <- str_remove(start, "^\\.*") %>% 
      extract2(1L)
    offset <- offset + str_length(head)
  }
  start %>% 
    str_split("") %>% 
    extract2(1L) %>% 
    equals("#") %>% 
    which() %>%
    add(offset - 1L) %>%
    sum()
}
grow_plants(20, puzzle_data$start, puzzle_data$rules)
## [1] 1987

2.2 Part 2

2.2.1 Description

— Part Two —

You realize that 20 generations aren’t enough. After all, these plants will need to last another 1500 years to even reach your timeline, not to mention your future.

After fifty billion (50000000000) generations, what is the sum of the numbers of all pots which contain a plant?

2.2.2 Solution

For the second part we must be way smarter, as it is not feasible to run 50 billion runs. We can keep track about seen plant configurations and as soon as we see the first repeated configuration we can fast forward. We just have to recall the offset change and multiply that by the remaining cycles to get the proper offset. As the numbers are potentially rather big, we have to use integer64 logic and re-write the previous code to deal with these large numbers.

grow_plants_large <- function(n, start = puzzle_data$start, rules = puzzle_data$rules) {
  ## make sure to pass n as integer64 too
  offset <- as.integer64(0L)
  i <- as.integer64(0L)
  make_key <- function(x) {
    paste0("K_", digest(x))
  }
  hash <- new.env()

  hash[[make_key(start)]] <- c(offset = offset, idx = i)
  while (i < n) {
    offset <- offset - as.integer64(2)
    start <- paste0("....", start, "....")
    new_gen <- ""
    for (j in 3:(nchar(start) - 2L)) {
      token <- str_sub(start, j - 2, j + 2L)
      if (!token %in% names(rules)) {
        new_gen <- paste0(new_gen, ".")
      } else {
        new_gen <- paste0(new_gen, rules[token])
      }
    }
    ## remove dots at the end
    start <- str_remove(new_gen, "\\.*$") %>% 
      extract2(1L)
    ## get number of dots in the beginning
    head <- str_extract(start, "^\\.*") %>% 
      extract2(1L)
    start <- str_remove(start, "^\\.*") %>% 
      extract2(1L)
    offset <- offset + as.integer64(str_length(head))
    if (exists(make_key(start), hash)) {
      vals <- hash[[make_key(start)]]
      cycle_length <- i - vals["idx"]
      offset_delta <- offset - vals["offset"]
      remaining_cycles <- (n - i - as.integer64(1L)) %/% cycle_length
      i <- i + remaining_cycles * cycle_length
      offset <- offset + remaining_cycles * offset_delta
    } else {
      hash[[make_key(start)]] <- c(offset = offset, idx = i)
    }
    i <- i + as.integer64(1L)
  }
  start %>% 
    str_split("") %>% 
    extract2(1L) %>% 
    equals("#") %>% 
    which() %>%
    as.integer64() %>% 
    add(offset - as.integer64(1L)) %>%
    sum()
}

grow_plants_large(as.integer64(50000000000), puzzle_data$start, puzzle_data$rules)
## integer64
## [1] 1150000000358