Task 17

Thorn Thaler - <

2026-01-26

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)
  }
  text_block %>% 
    str_split("") %>% 
    extract2(1L)
}

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

2 Puzzle Day 17

2.1 Part 1

2.1.1 Description

— Day 17: Pyroclastic Flow —

Your handheld device has located an alternative exit from the cave for you and the elephants. The ground is rumbling almost continuously now, but the strange valves bought you some time. It’s definitely getting warmer in here, though.

The tunnels eventually open into a very tall, narrow chamber. Large, oddly-shaped rocks are falling into the chamber from above, presumably due to all the rumbling. If you can’t work out where the rocks will fall next, you might be crushed!

The five types of rocks have the following peculiar shapes, where # is rock and . is empty space:

####

.#.
###
.#.

..#
..#
###

#
#
#
#

##
##

The rocks fall in the order shown above: first the - shape, then the + shape, and so on. Once the end of the list is reached, the same order repeats: the - shape falls first, sixth, 11th, 16th, etc.

The rocks don’t spin, but they do get pushed around by jets of hot gas coming out of the walls themselves. A quick scan reveals the effect the jets of hot gas will have on the rocks as they fall (your puzzle input).

For example, suppose this was the jet pattern in your cave:

>>><<><>><<<>><>>><<<>>><<<><<<>><>><<>>

In jet patterns, < means a push to the left, while > means a push to the right. The pattern above means that the jets will push a falling rock right, then right, then right, then left, then left, then right, and so on. If the end of the list is reached, it repeats.

The tall, vertical chamber is exactly seven units wide. Each rock appears so that its left edge is two units away from the left wall and its bottom edge is three units above the highest rock in the room (or the floor, if there isn’t one).

After a rock appears, it alternates between being pushed by a jet of hot gas one unit (in the direction indicated by the next symbol in the jet pattern) and then falling one unit down. If any movement would cause any part of the rock to move into the walls, floor, or a stopped rock, the movement instead does not occur. If a downward movement would have caused a falling rock to move into the floor or an already-fallen rock, the falling rock stops where it is (having landed on something) and a new rock immediately begins falling.

Drawing falling rocks with @ and stopped rocks with #, the jet pattern in the example above manifests as follows:

The first rock begins falling:
|..@@@@.|
|.......|
|.......|
|.......|
+-------+

Jet of gas pushes rock right:
|...@@@@|
|.......|
|.......|
|.......|
+-------+

Rock falls 1 unit:
|...@@@@|
|.......|
|.......|
+-------+

Jet of gas pushes rock right, but nothing happens:
|...@@@@|
|.......|
|.......|
+-------+

Rock falls 1 unit:
|...@@@@|
|.......|
+-------+

Jet of gas pushes rock right, but nothing happens:
|...@@@@|
|.......|
+-------+

Rock falls 1 unit:
|...@@@@|
+-------+

Jet of gas pushes rock left:
|..@@@@.|
+-------+

Rock falls 1 unit, causing it to come to rest:
|..####.|
+-------+

A new rock begins falling:
|...@...|
|..@@@..|
|...@...|
|.......|
|.......|
|.......|
|..####.|
+-------+

Jet of gas pushes rock left:
|..@....|
|.@@@...|
|..@....|
|.......|
|.......|
|.......|
|..####.|
+-------+

Rock falls 1 unit:
|..@....|
|.@@@...|
|..@....|
|.......|
|.......|
|..####.|
+-------+

Jet of gas pushes rock right:
|...@...|
|..@@@..|
|...@...|
|.......|
|.......|
|..####.|
+-------+

Rock falls 1 unit:
|...@...|
|..@@@..|
|...@...|
|.......|
|..####.|
+-------+

Jet of gas pushes rock left:
|..@....|
|.@@@...|
|..@....|
|.......|
|..####.|
+-------+

Rock falls 1 unit:
|..@....|
|.@@@...|
|..@....|
|..####.|
+-------+

Jet of gas pushes rock right:
|...@...|
|..@@@..|
|...@...|
|..####.|
+-------+

Rock falls 1 unit, causing it to come to rest:
|...#...|
|..###..|
|...#...|
|..####.|
+-------+

A new rock begins falling:
|....@..|
|....@..|
|..@@@..|
|.......|
|.......|
|.......|
|...#...|
|..###..|
|...#...|
|..####.|
+-------+

The moment each of the next few rocks begins falling, you would see this:

|..@....|
|..@....|
|..@....|
|..@....|
|.......|
|.......|
|.......|
|..#....|
|..#....|
|####...|
|..###..|
|...#...|
|..####.|
+-------+

|..@@...|
|..@@...|
|.......|
|.......|
|.......|
|....#..|
|..#.#..|
|..#.#..|
|#####..|
|..###..|
|...#...|
|..####.|
+-------+

|..@@@@.|
|.......|
|.......|
|.......|
|....##.|
|....##.|
|....#..|
|..#.#..|
|..#.#..|
|#####..|
|..###..|
|...#...|
|..####.|
+-------+

|...@...|
|..@@@..|
|...@...|
|.......|
|.......|
|.......|
|.####..|
|....##.|
|....##.|
|....#..|
|..#.#..|
|..#.#..|
|#####..|
|..###..|
|...#...|
|..####.|
+-------+

|....@..|
|....@..|
|..@@@..|
|.......|
|.......|
|.......|
|..#....|
|.###...|
|..#....|
|.####..|
|....##.|
|....##.|
|....#..|
|..#.#..|
|..#.#..|
|#####..|
|..###..|
|...#...|
|..####.|
+-------+

|..@....|
|..@....|
|..@....|
|..@....|
|.......|
|.......|
|.......|
|.....#.|
|.....#.|
|..####.|
|.###...|
|..#....|
|.####..|
|....##.|
|....##.|
|....#..|
|..#.#..|
|..#.#..|
|#####..|
|..###..|
|...#...|
|..####.|
+-------+

|..@@...|
|..@@...|
|.......|
|.......|
|.......|
|....#..|
|....#..|
|....##.|
|....##.|
|..####.|
|.###...|
|..#....|
|.####..|
|....##.|
|....##.|
|....#..|
|..#.#..|
|..#.#..|
|#####..|
|..###..|
|...#...|
|..####.|
+-------+

|..@@@@.|
|.......|
|.......|
|.......|
|....#..|
|....#..|
|....##.|
|##..##.|
|######.|
|.###...|
|..#....|
|.####..|
|....##.|
|....##.|
|....#..|
|..#.#..|
|..#.#..|
|#####..|
|..###..|
|...#...|
|..####.|
+-------+

To prove to the elephants your simulation is accurate, they want to know how tall the tower will get after 2022 rocks have stopped (but before the 2023rd rock begins falling). In this example, the tower of rocks will be 3068 units tall.

How many units tall will the tower of rocks be after 2022 rocks have stopped falling?

2.1.2 Solution

For the first part we use a direct simulation. An upper bound for the height of the cave is sum of all rock heights multiplied by the number of rounds and divided by 5. This would be the largest required cave size, if all pieces land on top of each other.

Then we define rocks by logical matrices which we want to place in the cave (yet another logical matrix). To determine the starting point we just have to get the smallest row index where there is at least one piece. We use a two-column index matrix with the positions of the current rock in the cave (given its starting point determined by the height calculated earlier). We move this index matrix horizontally and vertically and check collisions by subsetting the cave with this index matrix and looking for rocks both in the cave at the current rock. Once the rock come to rest, we place it in the cave using logical entries. To determine the final height, we look again at the first row containing at least one TRUE value and subtract this from the total number of rows.

print.cave <- function(x, rock_idx = NULL, rock = NULL, ...) {
  cave <- if_else(c(x), "#", ".")
  dim(cave) <- dim(x)
  if (!is.null(rock_idx)) {
    rock_idx <- rock_idx[c(rock), , drop = FALSE]
    cave[rock_idx] <- "@"  
  }
  bottom <- rep(c("+", "-", "+"), c(1L, ncol(x), 1L))
  cave <- cbind("|", cave, "|") %>% 
    rbind(bottom)
  apply(cave, 1L, paste, collapse = "") %>% 
    paste(collapse = "\n") %>% 
    cat("\n")
  invisible(x)
}

simulate_rock_tetris <- function(jet, nr_rounds) {
  rocks <- list(
    matrix(TRUE, 1L, 4L),
    matrix(c(FALSE, TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, TRUE, FALSE), 3L, 3L),
    matrix(c(FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE), 3L, 3L),
    matrix(TRUE, 4L, 1L),
    matrix(TRUE, 2L, 2L)
  )
  ## each round we drop a rock of height 1 - 4
  ## each 5 rounds we have dropped all rocks with a total of 13 height
  ## that is a conservative estimation of the maximum height is 
  ## ceiling(13 * nr_rounds / 5) + 3L 
  bottom <- ceiling(13L * nr_rounds / 5L) + 3L
  cave <- matrix(FALSE, bottom, 7L)
  class(cave) <- "cave"
  dirs <- rbind(
    ">" = c(0L, 1L),
    "<" = c(0L, -1L)
  )
  cur_rock <- 1L
  get_idx <- function(pos, rock) {
    r_idx <- row(rock) - nrow(rock)
    c_idx <- col(rock) - 1L
    cbind(pos[1L] + c(r_idx),
          pos[2L] + c(c_idx))
  }
  jet_pos <- 1L
  for (rnd in seq_len(nr_rounds)) {
    rock <- rocks[[cur_rock]]
    rows_n <- rowSums(cave)
    if (all(rows_n == 0L)) {
      height <- bottom
    } else {
      height <- which(rows_n > 0L) %>% 
        min() %>% 
        subtract(1L)
    }
    corner_pos <- cbind(height - 3L, 3L)
    at_rest <- FALSE
    while (!at_rest) {
      ## 1. Move horizontally
      cur_rock_pos <- get_idx(corner_pos, rock)
      next_rock_pos <- sweep(cur_rock_pos, 2L, dirs[jet[jet_pos], , drop = FALSE], `+`)
      if (all(next_rock_pos[, 2L] >= 1L & next_rock_pos[, 2L] <= ncol(cave))) {
        ## rock is in bounds
        if (!any(cave[next_rock_pos] & rock)) {
          ## new position is free
          cur_rock_pos <- next_rock_pos
          corner_pos <- corner_pos + dirs[jet[jet_pos], , drop = FALSE]
        }
      }
      ## 2. move vertically
      next_rock_pos <- sweep(cur_rock_pos, 2L, cbind(1L, 0L), `+`)
      at_rest <- TRUE
      if (all(next_rock_pos[, 1L] <= nrow(cave))) {
        ## rock is in bounds
        if (!any(cave[next_rock_pos] & rock)) {
          ## new position is free
          cur_rock_pos <- next_rock_pos
          corner_pos <- corner_pos + cbind(1L, 0L)
          at_rest <- FALSE
        }
      }
      jet_pos <- (jet_pos %% length(jet)) + 1L
    }
    cave[cur_rock_pos] <- cave[cur_rock_pos] | rock
    cur_rock <- (cur_rock %% length(rocks)) + 1L
  }
  rows_n <- rowSums(cave)
  last_row <- which(rows_n > 0L) %>% 
        min()
  bottom - last_row + 1L
}

simulate_rock_tetris(puzzle_data, 2022L)
## [1] 3159

2.2 Part 2

2.2.1 Description

— Part Two —

The elephants are not impressed by your simulation. They demand to know how tall the tower will be after 1000000000000 rocks have stopped! Only then will they feel confident enough to proceed through the cave.

In the example above, the tower would be 1514285714288 units tall!

How tall will the tower be after 1000000000000 rocks have stopped?

2.2.2 Solution

For the second part brute-force is out-of question, so we need to find recurring patterns. At each iteration we look at the top 4 rows and store them together with the next rock and jet. If at any stage we get a state which we have seen before, i.e. same surface same next rock and same next jet we can fast forward by calculating the cycle length and gain.

calculate_height <- function(jet, nr_rounds) {
  rocks <- list(
    matrix(TRUE, 1L, 4L),
    matrix(c(FALSE, TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, TRUE, FALSE), 3L, 3L),
    matrix(c(FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE), 3L, 3L),
    matrix(TRUE, 4L, 1L),
    matrix(TRUE, 2L, 2L)
  )
  hash <- new.env(parent = emptyenv())
  ## set max rows as before assuming 10k rounds of active placing
  bottom <- ceiling(13L * 10000L / 5L) + 3L
  cave <- matrix(FALSE, bottom, 7L)
  class(cave) <- "cave"
  dirs <- rbind(
    ">" = c(0L, 1L),
    "<" = c(0L, -1L)
  )
  cur_rock <- 1L
  get_idx <- function(pos, rock) {
    r_idx <- row(rock) - nrow(rock)
    c_idx <- col(rock) - 1L
    cbind(pos[1L] + c(r_idx),
          pos[2L] + c(c_idx))
  }
  jet_pos <- 1L
  added_height <- 0L
  rnd <- 1L
  surface_size <- 4L
  while (rnd <= nr_rounds) {
    rock <- rocks[[cur_rock]]
    rows_n <- rowSums(cave)
    if (all(rows_n == 0L)) {
      height <- bottom
    } else {
      height <- which(rows_n > 0L) %>% 
        min() %>% 
        subtract(1L)
    }
    corner_pos <- cbind(height - 3L, 3L)
    at_rest <- FALSE
    horizontal <- vertical <- 0L
    while (!at_rest) {
      ## 1. Move horizontally
      cur_rock_pos <- get_idx(corner_pos, rock)
      next_rock_pos <- sweep(cur_rock_pos, 2L, dirs[jet[jet_pos], , drop = FALSE], `+`)
      if (all(next_rock_pos[, 2L] >= 1L & next_rock_pos[, 2L] <= ncol(cave))) {
        ## rock is in bounds
        if (!any(cave[next_rock_pos] & rock)) {
          ## new position is free
          cur_rock_pos <- next_rock_pos
          corner_pos <- corner_pos + dirs[jet[jet_pos], , drop = FALSE]
          horizontal <- horizontal + (jet[jet_pos] == ">")
        }
      }
      ## 2. move vertically
      next_rock_pos <- sweep(cur_rock_pos, 2L, cbind(1L, 0L), `+`)
      at_rest <- TRUE
      if (all(next_rock_pos[, 1L] <= nrow(cave))) {
        ## rock is in bounds
        if (!any(cave[next_rock_pos] & rock)) {
          ## new position is free
          cur_rock_pos <- next_rock_pos
          corner_pos <- corner_pos + cbind(1L, 0L)
          at_rest <- FALSE
          vertical <- vertical + 1L 
        }
      }
      jet_pos <- (jet_pos %% length(jet)) + 1L
    }
    cave[cur_rock_pos] <- cave[cur_rock_pos] | rock
    rows_n <- rowSums(cave)
    last_row <- which(rows_n > 0L) %>% 
      min()
    cur_rock <- (cur_rock %% length(rocks)) + 1L
    rnd <- rnd + 1L
    if (last_row < bottom - surface_size) {
      top_rows <- cave[last_row:(last_row + surface_size), ]
      key <- digest(list(top_rows, cur_rock, jet_pos))
      prev <- hash[[key]]
      if (!is.null(prev)) {
        rnd_prev <- prev$rnd
        h_prev <- prev$height
        cur_h <- bottom - last_row + 1L + added_height
        cycle_len  <- rnd - rnd_prev 
        cycle_gain <- (cur_h - h_prev)
        remain  <- nr_rounds - rnd
        if (cycle_len > 0L && remain >= cycle_len) {
          cycles <- remain %/% cycle_len
          added_height <- added_height + cycles * cycle_gain
          rnd <- rnd + cycles * cycle_len
          ## empty hash
          hash <- new.env(parent = emptyenv())
        }
      } else {
        hash[[key]] <- list(rnd = rnd, height = bottom - last_row + 1L + added_height)
      }
    }

  }
  rows_n <- rowSums(cave)
  last_row <- which(rows_n > 0L) %>% 
    min()
  height <- bottom - last_row + 1L
  as.integer64(height + added_height)
}

calculate_height(puzzle_data, 1000000000000)
## integer64
## [1] 1566272189352