Task 13

Thorn Thaler - <

2025-10-10

1 Setup

1.1 Libraries

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

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("") %>% 
    do.call(rbind, .)
}

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

2 Puzzle Day 13

2.1 Part 1

2.1.1 Description

— Day 13: Mine Cart Madness —

A crop of this size requires significant logistics to transport produce, soil, fertilizer, and so on. The Elves are very busy pushing things around in carts on some kind of rudimentary system of tracks they’ve come up with.

Seeing as how cart-and-track systems don’t appear in recorded history for another 1000 years, the Elves seem to be making this up as they go along. They haven’t even figured out how to avoid collisions yet.

You map out the tracks (your puzzle input) and see where you can help.

Tracks consist of straight paths (| and -), curves (/ and \), and intersections (+). Curves connect exactly two perpendicular pieces of track; for example, this is a closed loop:

/----\
|    |
|    |
\----/

Intersections occur when two perpendicular paths cross. At an intersection, a cart is capable of turning left, turning right, or continuing straight. Here are two loops connected by two intersections:

/-----\
|     |
|  /--+--\
|  |  |  |
\--+--/  |
   |     |
   \-----/

Several carts are also on the tracks. Carts always face either up (^), down (v), left (<), or right (>). (On your initial map, the track under each cart is a straight path matching the direction the cart is facing.)

Each time a cart has the option to turn (by arriving at any intersection), it turns left the first time, goes straight the second time, turns right the third time, and then repeats those directions starting again with left the fourth time, straight the fifth time, and so on. This process is independent of the particular intersection at which the cart has arrived - that is, the cart has no per-intersection memory.

Carts all move at the same speed; they take turns moving a single step at a time. They do this based on their current location: carts on the top row move first (acting from left to right), then carts on the second row move (again from left to right), then carts on the third row, and so on. Once each cart has moved one step, the process repeats; each of these loops is called a tick.

For example, suppose there are two carts on a straight track:

|  |  |  |  |
v  |  |  |  |
|  v  v  |  |
|  |  |  v  X
|  |  ^  ^  |
^  ^  |  |  |
|  |  |  |  |

First, the top cart moves. It is facing down (v), so it moves down one square. Second, the bottom cart moves. It is facing up (^), so it moves up one square. Because all carts have moved, the first tick ends. Then, the process repeats, starting with the first cart. The first cart moves down, then the second cart moves up - right into the first cart, colliding with it! (The location of the crash is marked with an X.) This ends the second and last tick.

Here is a longer example:

/->-\        
|   |  /----\
| /-+--+-\  |
| | |  | v  |
\-+-/  \-+--/
  \------/   

/-->\        
|   |  /----\
| /-+--+-\  |
| | |  | |  |
\-+-/  \->--/
  \------/   

/---v        
|   |  /----\
| /-+--+-\  |
| | |  | |  |
\-+-/  \-+>-/
  \------/   

/---\        
|   v  /----\
| /-+--+-\  |
| | |  | |  |
\-+-/  \-+->/
  \------/   

/---\        
|   |  /----\
| /->--+-\  |
| | |  | |  |
\-+-/  \-+--^
  \------/   

/---\        
|   |  /----\
| /-+>-+-\  |
| | |  | |  ^
\-+-/  \-+--/
  \------/   

/---\        
|   |  /----\
| /-+->+-\  ^
| | |  | |  |
\-+-/  \-+--/
  \------/   

/---\        
|   |  /----<
| /-+-->-\  |
| | |  | |  |
\-+-/  \-+--/
  \------/   

/---\        
|   |  /---<\
| /-+--+>\  |
| | |  | |  |
\-+-/  \-+--/
  \------/   

/---\        
|   |  /--<-\
| /-+--+-v  |
| | |  | |  |
\-+-/  \-+--/
  \------/   

/---\        
|   |  /-<--\
| /-+--+-\  |
| | |  | v  |
\-+-/  \-+--/
  \------/   

/---\        
|   |  /<---\
| /-+--+-\  |
| | |  | |  |
\-+-/  \-<--/
  \------/   

/---\        
|   |  v----\
| /-+--+-\  |
| | |  | |  |
\-+-/  \<+--/
  \------/   

/---\        
|   |  /----\
| /-+--v-\  |
| | |  | |  |
\-+-/  ^-+--/
  \------/   

/---\        
|   |  /----\
| /-+--+-\  |
| | |  X |  |
\-+-/  \-+--/
  \------/   

After following their respective paths for a while, the carts eventually crash. To help prevent crashes, you’d like to know the location of the first crash. Locations are given in X,Y coordinates, where the furthest left column is X=0 and the furthest top row is Y=0:

           111
 0123456789012
0/---\        
1|   |  /----\
2| /-+--+-\  |
3| | |  X |  |
4\-+-/  \-+--/
5  \------/   

In this example, the location of the first crash is 7,3.

2.1.2 Solution

For the first part, we keep a matrix of the position of the carts together with their current orientation. Each tick they move by one field, where we check the condition, if it is an intersection we turn the cart and if it is another cart we report a collision. To mimick the order of movement, we sort the cart matrix by row and column.

In a first attempt we used vectorization for the movements, but then we missed collisions of passing cars. Hence, we decided to go for moving one cart at a time.

We use an environment to pass the cart positions and the map to the move_cart function to avoid copying large matrices over and over again.

move_cart <- function(track, start_from = 1L) {
  dirs <- c("^" = 1L, ">" = 2L, "v" = 3L, "<" = 4L)
  offset <- rbind(
    "^" = c(-1L, 0L),
    ">" = c(0L, 1L),
    "v" = c(1L, 0L),
    "<" = c(0L, -1L)
  )
  crash <- FALSE
  for (cart_idx in seq(start_from, nrow(track$carts))) {
    ## unfortunately we need to cycle cart by cart to detect collisions
    ## if we do it vectorized we may overlook swap collisions
    if (track$carts[cart_idx, "crashed"] == 1L) {
      next
    }
    track$carts[cart_idx, 1:2] <- track$carts[cart_idx, 1:2] + 
      offset[track$carts[cart_idx, "dir"], ]
    crashed <- duplicated(track$carts[track$carts[, "crashed"] != 1L, 1:2])
    if (any(crashed)) {
      crash <- TRUE
      crashed_cart <- cart_idx
      track$carts[duplicated(track$carts[, 1:2]) |
                    duplicated(track$carts[, 1:2], fromLast = TRUE), 
                  "crashed"] <- 1L
      attr(crash, "crashed_cart") <- crashed_cart
      return(crash)
    }
    new_pos <- track$map[track$carts[cart_idx, 1:2, drop = FALSE]]
    can_turn <- new_pos == "+"
    must_turn <- new_pos %in% c("\\", "/")
    if (must_turn) {
      track$carts[cart_idx, "dir"] <- (
        track$carts[cart_idx, "dir"] +
          case_when(
            new_pos == "/" & track$carts[cart_idx, "dir"] %in% c(1L, 3L) ~ 1L,
            new_pos == "/" & track$carts[cart_idx, "dir"] %in% c(2L, 4L) ~ -1L,
            new_pos == "\\" & track$carts[cart_idx, "dir"] %in% c(2L, 4L) ~ 1L,
            new_pos == "\\" & track$carts[cart_idx, "dir"] %in% c(1L, 3L) ~ -1L
          ) - 1L) %% 4L + 1L
    }
    if (can_turn) {
      track$carts[cart_idx, "dir"] <- (
        track$carts[cart_idx, "dir"] +
          case_when(
            track$carts[cart_idx, "turn_idx"] %% 3L == 0L ~ -1L,
            track$carts[cart_idx, "turn_idx"] %% 3L == 1L ~ 0L,
            track$carts[cart_idx, "turn_idx"] %% 3L == 2L ~ 1L
          ) - 1L) %% 4L + 1L
      track$carts[cart_idx, "turn_idx"] <- track$carts[cart_idx, "turn_idx"] + 1L
    }
  }
  track$carts <- track$carts[order(track$carts[, 2], 
                                          track$carts[, 1]), , drop = FALSE]
  attr(crash, "crashed_cart") <- NULL
  crash
}

setup_track <- function(orig_map) {
  carts <- which(orig_map == ">" |
                   orig_map == "v" |
                   orig_map == "<"|
                   orig_map == "^", arr.ind = TRUE)
  ## remove cart from map
  map <- orig_map
  map[carts] <- if_else(map[carts] %in% c("<", ">"), "-", "|")
  dirs <- c("^" = 1L, ">" = 2L, "v" = 3L, "<" = 4L)
  carts <- cbind(carts, turn_idx = 0L, dir = dirs[orig_map[carts]], crashed = 0L)
  carts <- carts[order(carts[, 2], carts[, 1]), , drop = FALSE]
  rownames(carts) <- LETTERS[seq_len(nrow(carts))]
  track <- new.env()
  track$carts <- carts
  track$map <- map
  track
}

get_first_crash <- function(orig_map = puzzle_data) {
  track <- setup_track(orig_map)
  crash <- FALSE
  tick <- 0L
  while (!crash) {
    crash <- move_cart(track, 1L)
    tick <- tick + 1L 
  }
  crash_idx <- which(track$carts[, "crashed"] == 1L)[[1L]]
  paste(track$carts[crash_idx, 2:1] - 1L, collapse = ",")
}

get_first_crash(puzzle_data)
## [1] "14,42"

2.2 Part 2

2.2.1 Description

— Part Two —

There isn’t much you can do to prevent crashes in this ridiculous system. However, by predicting the crashes, the Elves know where to be in advance and instantly remove the two crashing carts the moment any crash occurs.

They can proceed like this for a while, but eventually, they’re going to run out of carts. It could be useful to figure out where the last cart that hasn’t crashed will end up.

For example:

/>-<\  
|   |  
| /<+-\
| | | v
\>+</ |
  |   ^
  \<->/

/---\  
|   |  
| v-+-\
| | | |
\-+-/ |
  |   |
  ^---^

/---\  
|   |  
| /-+-\
| v | |
\-+-/ |
  ^   ^
  \---/

/---\  
|   |  
| /-+-\
| | | |
\-+-/ ^
  |   |
  \---/

After four very expensive crashes, a tick ends with only one cart remaining; its final location is 6,4.

What is the location of the last cart at the end of the first tick where it is the only cart left?

2.2.2 Solution

We reuse the move_cart function from part 1. We just have to resume the moving right after the crashed cart and keep count of the surviving carts. In the end we have to check whether the crash ahppened before the last cart could move. If so, let the last cart move once more.

get_surving_cart <- function(orig_map = puzzle_data) {
  track <- setup_track(orig_map)
  nr_carts <- nrow(track$carts)
  tick <- 0L
  first_cart <- 1L
  while (nr_carts > 1L) {
    crash <- move_cart(track, first_cart)
    if (crash) {
      crashed_cart <- attr(crash, "crashed_cart")
      first_cart <- crashed_cart
      nr_carts <- nr_carts - 2L
    } else {
      first_cart <- 1L
    }
    tick <- tick + 1L
  }
  surv_idx <- which(track$carts[, "crashed"] == 0L)
  if (surv_idx > attr(crash, "crashed_cart")) {
    move_cart(track, surv_idx)
  }
  paste(track$carts[surv_idx, 2:1] - 1L, collapse = ",")
}
get_surving_cart(puzzle_data)
## [1] "8,7"