Task 15

Thorn Thaler - <

2025-01-08

1 Setup

1.1 Libraries

library(httr)
library(xml2)
library(magrittr)
library(dplyr)
library(purrr)
library(stringr)
library(knitr)
library(cli)
library(bit64)
library(ggplot2)
library(gganimate)

1.2 Retrieve Data from AoC

session_cookie <- set_cookies(session = keyring::key_get("AoC-GitHub-Cookie"))
base_url <- paste0("https://adventofcode.com/2024/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 %>% 
      unlist() %>% 
      str_split("\n") %>% 
      extract2(1L) %>% 
      head(-1L)
  }
  split_idx <- which(!nzchar(text_block))
  warehouse <- text_block[seq(1L, split_idx - 1L)]
  movements <- text_block[seq(split_idx + 1L, length(text_block))]
  list(
    warehouse = str_split(warehouse, "") %>% 
      do.call(rbind, .),
    movements = str_split(movements, "") %>% 
      unlist()
  )
}

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

2 Puzzle Day 15

2.1 Part 1

2.1.1 Description

— Day 15: Warehouse Woes —

You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well?

You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help.

Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That’s why these lanternfish have built elaborate warehouse complexes operated by robots!

These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies.

Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot’s movements, maybe they could find a safe option.

The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict.

For example:

##########
#..O..O.O#
#......O.#
#.OO..O.O#
#..O@..O.#
#O#..O...#
#O..O..O.#
#.OO.O.OO#
#....O...#
##########

<vv>^<v^>v>^vv^v>v<>v^v<v<^vv<<<^><<><>>v<vvv<>^v^>^<<<><<v<<<v^vv^v>^
vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<<v<^v>^<^^>>>^<v<v
><>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^<v>v^^<^^vv<
<<v<^>>^^^^>>>v^<>vvv^><v<<<>^^^vv^<vvv>^>v<^^^^v<>^>vvvv><>>v^<<^^^^^
^><^><>>><>^^<<^^v>>><^<v>^<vv>>v>>>^v><>^v><<<<v>>v<v<v>vvv>^<><<>^><
^>><>^v<><^vvv<^^<><v<<<<<><^v<<<><<<^^<v<^^^><^>>^<v^><<<^>>^v<v^v<v^
>^>>^v>vv>^<<^v<>><<><<v<<v><>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^
<><^^>^^^<><vvvvv^v<v<<>^v<v>v<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<>
^^>vv<^v^v<vv>^<><v<^v>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<><<v>
v^^>>><<^^<>>^v^<v^vv<>v^<<>^<^v^v><^<<<><<^<v><v<>vv>>v><v^<vv<>v^<<^

As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you.

The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.)

Here is a smaller example to get started:

########
#..O.O.#
##@.O..#
#...O..#
#.#.O..#
#...O..#
#......#
########

<^^>>>vv<v>>v<<

Were the robot to attempt the given sequence of moves, it would push around the boxes as follows:

Initial state:
########
#..O.O.#
##@.O..#
#...O..#
#.#.O..#
#...O..#
#......#
########

Move <:
########
#..O.O.#
##@.O..#
#...O..#
#.#.O..#
#...O..#
#......#
########

Move ^:
########
#.@O.O.#
##..O..#
#...O..#
#.#.O..#
#...O..#
#......#
########

Move ^:
########
#.@O.O.#
##..O..#
#...O..#
#.#.O..#
#...O..#
#......#
########

Move >:
########
#..@OO.#
##..O..#
#...O..#
#.#.O..#
#...O..#
#......#
########

Move >:
########
#...@OO#
##..O..#
#...O..#
#.#.O..#
#...O..#
#......#
########

Move >:
########
#...@OO#
##..O..#
#...O..#
#.#.O..#
#...O..#
#......#
########

Move v:
########
#....OO#
##..@..#
#...O..#
#.#.O..#
#...O..#
#...O..#
########

Move v:
########
#....OO#
##..@..#
#...O..#
#.#.O..#
#...O..#
#...O..#
########

Move <:
########
#....OO#
##.@...#
#...O..#
#.#.O..#
#...O..#
#...O..#
########

Move v:
########
#....OO#
##.....#
#..@O..#
#.#.O..#
#...O..#
#...O..#
########

Move >:
########
#....OO#
##.....#
#...@O.#
#.#.O..#
#...O..#
#...O..#
########

Move >:
########
#....OO#
##.....#
#....@O#
#.#.O..#
#...O..#
#...O..#
########

Move v:
########
#....OO#
##.....#
#.....O#
#.#.O@.#
#...O..#
#...O..#
########

Move <:
########
#....OO#
##.....#
#.....O#
#.#O@..#
#...O..#
#...O..#
########

Move <:
########
#....OO#
##.....#
#.....O#
#.#O@..#
#...O..#
#...O..#
########

The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this:

##########
#.O.O.OOO#
#........#
#OO......#
#OO@.....#
#O#.....O#
#O.....OO#
#O.....OO#
#OO....OO#
##########

The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.)

So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104.

#######
#...O..
#......

The lanternfish would like to know the sum of all boxes’ GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes’ GPS coordinates is 10092. In the smaller example, the sum is 2028.

Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes’ GPS coordinates?

2.1.2 Solution

The solution is rather straight forward. Let the robot move and on each step determine where he will move to: 1. If the new spot is empty, simply move to it. 1. If it is a wall, stay where you are. 1. If it is a crate, check for the first empty spot behind the crates and push the crates.

show_warehouse <- function(warehouse) {
  cat(
    apply(
      warehouse, 1, paste, collapse = ""
    ) %>% 
      paste(collapse = "\n"),
    "\n\n"
  )
}

plot_warehouse <- function(warehouse, direction) {
  if (!is.list(warehouse)) {
    warehouse <- list(warehouse)
  }
  stopifnot(length(warehouse) == length(direction))
  coords <- map(seq_along(warehouse), ~ tibble(
    x = rep(1:ncol(warehouse[[.x]]), each = nrow(warehouse[[.x]])),
    y = rep(nrow(warehouse[[.x]]):1, ncol(warehouse[[.x]])),
    value = c(warehouse[[.x]])
  ) %>% 
    mutate(fill = case_when(
      value == "@" ~ "firebrick",
      value %in% c("O", "[", "]") ~ "burlywood",
      value == "#" ~ "gray70",
      TRUE ~ NA_character_
    ),
    start = value == "@",
    dir = direction[[.x]],
    vj = case_when(
      dir == "^" ~ .75, 
      dir == "v" ~ .35,
      TRUE ~ .5),
    frame = .x)
  ) %>% 
    list_rbind()
  res <- ggplot(coords, aes(x = x, y = y)) + 
    geom_tile(aes(fill = fill), linewidth = .5, color = "black") +
    scale_fill_identity() + 
    theme_void() +
    coord_fixed() +
    geom_text(data = coords %>% filter(start),
              aes(label = dir, vjust = vj), 
              color = "white", size = 15) +
    geom_text(aes(label = label), 
              data = coords %>% 
                select(x, y) %>% 
                mutate(label = max(y) + 1 - y, x = 0) %>% 
                distinct(),
              color = "#007ACC",
              hjust = .5) +
    geom_text(aes(label = label), 
              data = coords %>% 
                select(x, y) %>% 
                mutate(label = max(y) + 1L - y, x = max(x) + 1) %>% 
                distinct(),
              color = "#007ACC",
              hjust = .5) +
    geom_text(aes(label = label), 
              data = coords %>% 
                select(x, y) %>% 
                mutate(label = x, y = 0) %>% 
                distinct(),
              color = "#007ACC",
              vjust = .5) +
    geom_text(aes(label = label), 
              data = coords %>% 
                select(x, y) %>% 
                mutate(label = x, y = max(y) + 1) %>% 
                distinct(),
              color = "#007ACC",
              vjust = .5) +
    labs(subtitle = "Step {frame}") +
    transition_manual(frame) +
    theme(
      plot.subtitle = element_text(color = "#007ACC"),
      plot.background = element_blank(),
      panel.background = element_blank()
    )
                                     
  invisible(res)
}

push_boxes <- function(warehouse, movements, do_print = FALSE, save_plot = FALSE) {
  dirs <- rbind(
    cbind(-1L, 0L),
    cbind(0L, 1L),
    cbind(1L, 0L),
    cbind(0L, -1L)
  ) %>% 
    set_rownames(c("^", ">", "v", "<"))
  current_pos <- which(warehouse == "@", arr.ind = TRUE)
  i <- 1
  all_warehouses <- list(warehouse)
  move <- function(current_pos, direction) {
    dir <- dirs[direction, , drop = FALSE]
    new_pos <- current_pos + dir
    new_field <- warehouse[new_pos]
    if (new_field == ".") {
      ## field is empty => move
      warehouse[rbind(current_pos, new_pos)] <<- c(".", "@")
    } else if (new_field == "#") {
      ## field is a wall => do not move
      new_pos <- current_pos
    } else if (new_field == "O") {
      ## field is a crate
      ## get distance to border
      if (any(dir < 0)) {
        ## we go left / up
        ref_point <- cbind(1L, 1L)
      } else {
        ref_point <- dim(warehouse)
      }
      distance_border <- abs(c((ref_point - current_pos) / dir))
      distance_border <- distance_border[is.finite(distance_border)]
      if (distance_border >= 3) {
        ## if we are at least 3 fields away from border 
        ## (for "# o @" there cannot be an empty space)
        ## all fields next to the current position until the border   
        idx <- map(seq(2L, distance_border - 1L), ~ current_pos + .x * dir) %>% 
          do.call(rbind, .)
        ## free spaces in the same row / col
        free_spaces <- warehouse[idx] == "."
        ## walls in the same row / col
        walls <- warehouse[idx] == "#"
        ## first free space
        first_free_space <- which.max(free_spaces)
        closest_wall <- which.max(walls)
        if (any(free_spaces) && (!any(walls) || first_free_space < closest_wall)) {
          ## if there is at least one free space _after_ a wall 
          warehouse[idx[seq(1L, first_free_space), , drop = FALSE]] <<- "O"
          warehouse[new_pos] <<- "@"
          warehouse[current_pos] <<- "."
        } else {
          ## if there's none, don't move
          new_pos <- current_pos
        }
      } else {
        new_pos <- current_pos
      }
    }
    if (do_print) {
      msg <- paste0("Step ", i, ": ", direction)
      cat(msg, "\n")
      show_warehouse(warehouse)
    }
    i <<- i + 1
    if (save_plot) {
      all_warehouses <<- c(all_warehouses, list(warehouse))
    }
    new_pos
  }
  reduce(movements, move, .init = current_pos)
  if (save_plot) {
    anim <- animate(plot_warehouse(all_warehouses, c("S", movements)), fps = 4, 
                    nframes = length(all_warehouses))
    
  } else {
    anim <- NULL
  }
  list(warehouse = warehouse, anim = anim)
}

calculate_gps <- function(warehouse) {
  pos <- which(warehouse == "O" | warehouse == "[", arr.ind = TRUE)
  sum((pos[, "row"] - 1L) * 100L + (pos[, "col"] - 1L))
}

solution1 <- push_boxes(puzzle_data$warehouse,
                        puzzle_data$movements, save_plot = FALSE)

calculate_gps(solution1$warehouse)
## [1] 1515788

For the fun of it, here is a GIF showing the robot at work for a smaller warehouse:

2.2 Part 2

2.2.1 Description

— Part Two —

The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse’s robot is also malfunctioning.

This warehouse’s layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot’s list of movements doesn’t change.

To get the wider warehouse’s map, start with your original map and, for each tile, make the following changes:

  • If the tile is #, the new map contains ## instead.
  • If the tile is O, the new map contains [] instead.
  • If the tile is ., the new map contains .. instead.
  • If the tile is @, the new map contains @. instead.

This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.)

The larger example from before would now look like this:

####################
##....[]....[]..[]##
##............[]..##
##..[][]....[]..[]##
##....[]@.....[]..##
##[]##....[]......##
##[]....[]....[]..##
##..[][]..[]..[][]##
##........[]......##
####################

Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation:

#######
#...#.#
#.....#
#..OO@#
#..O..#
#.....#
#######

<vv<<^^<<^^

After appropriately resizing this map, the robot would push around these boxes as follows:

Initial state:
##############
##......##..##
##..........##
##....[][]@.##
##....[]....##
##..........##
##############

Move <:
##############
##......##..##
##..........##
##...[][]@..##
##....[]....##
##..........##
##############

Move v:
##############
##......##..##
##..........##
##...[][]...##
##....[].@..##
##..........##
##############

Move v:
##############
##......##..##
##..........##
##...[][]...##
##....[]....##
##.......@..##
##############

Move <:
##############
##......##..##
##..........##
##...[][]...##
##....[]....##
##......@...##
##############

Move <:
##############
##......##..##
##..........##
##...[][]...##
##....[]....##
##.....@....##
##############

Move ^:
##############
##......##..##
##...[][]...##
##....[]....##
##.....@....##
##..........##
##############

Move ^:
##############
##......##..##
##...[][]...##
##....[]....##
##.....@....##
##..........##
##############

Move <:
##############
##......##..##
##...[][]...##
##....[]....##
##....@.....##
##..........##
##############

Move <:
##############
##......##..##
##...[][]...##
##....[]....##
##...@......##
##..........##
##############

Move ^:
##############
##......##..##
##...[][]...##
##...@[]....##
##..........##
##..........##
##############

Move ^:
##############
##...[].##..##
##...@.[]...##
##....[]....##
##..........##
##..........##
##############

This warehouse also uses GPS to locate the boxes. For these larger boxes, distances are measured from the edge of the map to the closest edge of the box in question. So, the box shown below has a distance of 1 from the top edge of the map and 5 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 5 = 105.

##########
##...[]...
##........

In the scaled-up version of the larger example from above, after the robot has finished all of its moves, the warehouse would look like this:

####################
##[].......[].[][]##
##[]...........[].##
##[]........[][][]##
##[]......[]....[]##
##..##......[]....##
##..[]............##
##..@......[].[][]##
##......[][]..[]..##
####################

The sum of these boxes’ GPS coordinates is 9021.

Predict the motion of the robot and boxes in this new, scaled-up warehouse. What is the sum of all boxes’ final GPS coordinates?

2.2.2 Solution

We have to adapt our code slightly. Left right pushes work the same way as before, we just have to make sure that we mark the new fields with the proper crate markers.

For upward and downward pushes, we have, however, to identify the current block. That is all crates which are vertically connected. We do that via a backtracking algorithm. If there is a wall above (below) any of the crates which we want to push, we return NA, thus, effectively avoiding a push.

enlarge_warehouse <- function(warehouse) {
  dd <- dim(warehouse)
  new_warehouse <- matrix(".",  dd[1L], 2L * dd[2L])
  idxs <- which(warehouse != "." , arr.ind = TRUE)
  for (i in seq_len(nrow(idxs))) {
    idx <- idxs[i, , drop = FALSE]
    pos_1 <- pos_2 <- idx
    pos_1[2L] <- 2L * pos_1[2L] - 1L
    pos_2[2L] <- 2L * pos_2[2L]
    pos <- rbind(pos_1, pos_2)
    if (warehouse[idx] == "O") {
      new_warehouse[pos] <- c("[", "]")
    } else if (warehouse[idx] == "@") {
      new_warehouse[pos[1L, , drop = FALSE]] <- "@" 
    } else {
      new_warehouse[pos] <- warehouse[idx]
    }
  }
  new_warehouse
}

push_big_boxes <- function(warehouse, movements, do_print = FALSE, save_plot = FALSE) {
  dirs <- rbind(
    cbind(-1L, 0L),
    cbind(0L, 1L),
    cbind(1L, 0L),
    cbind(0L, -1L)
  ) %>% 
    set_rownames(c("^", ">", "v", "<"))
  current_pos <- which(warehouse == "@", arr.ind = TRUE)
  i <- 1
  all_warehouses <- list(warehouse)
  move <- function(current_pos, direction) {
    dir <- dirs[direction, , drop = FALSE]
    new_pos <- current_pos + dir
    new_field <- warehouse[new_pos]
    if (new_field == ".") {
      ## field is empty => move
      warehouse[rbind(current_pos, new_pos)] <<- c(".", "@")
    } else if (new_field == "#") {
      ## field is a wall => do not move
      new_pos <- current_pos
    } else if (new_field %in% c("[", "]")) {
      ## field is a crate
      if (direction %in% c("<", ">")) {
        ## get distance to border
        if (any(dir < 0)) {
          ## we go left / up
          ref_point <- cbind(1L, 1L)
        } else {
          ref_point <- dim(warehouse)
        }
        distance_border <- abs(c((ref_point - current_pos) / dir))
        distance_border <- distance_border[is.finite(distance_border)]
        ## left / right
        if (distance_border >= 5) {
          ## if we are at least 5 fields away from border 
          ## (for "# # [ ] @" there cannot be an empty space)
          ## all fields next to the current position until the border   
          idx <- map(seq(1L, distance_border - 1L), ~ current_pos + .x * dir) %>% 
            do.call(rbind, .)
          ## free spaces in the same row / col
          free_spaces <- warehouse[idx] == "."
          ## walls in the same row / col
          walls <- warehouse[idx] == "#"
          ## first free space
          first_free_space <- which.max(free_spaces)
          closest_wall <- which.max(walls)
          if (any(free_spaces) && (!any(walls) || first_free_space < closest_wall)) {
            ## if there is at least one free space _after_ a wall 
            
            block_idx <- seq(1L, first_free_space)
            stopifnot(length(block_idx) %% 2L == 1L)
            block <- rep(c("[", "]"), (length(block_idx) - 1L) / 2L)
            block_idx <- idx[tail(block_idx, -1L), , drop = FALSE]
            warehouse[block_idx[order(block_idx[, 2]), , drop = FALSE]] <<- block
            warehouse[new_pos] <<- "@"
            warehouse[current_pos] <<- "."
          } else {
            ## if there's none, don't move
            new_pos <- current_pos
          }
        } else {
          new_pos <- current_pos
        }
      } else {
        ## up / down
        get_block <- function(current_pos) {
          res <- NULL
          if (warehouse[current_pos] %in% c("[", "]")) {
            ## we hit (yet another) a box
            left_part <- right_part <- current_pos
            if (warehouse[current_pos] == "[") {
              right_part[2L] <- right_part[2L] + 1L
            } else {
              left_part[2L] <- left_part[2L] - 1L
            }
            me <- rbind(left_part, right_part)
            res <- rbind(me,
                         Recall(left_part + dir),
                         Recall(right_part + dir))
          } else if (warehouse[current_pos] == "#") {
            ## there is a wall in the way so we cannot move
            res <- NA
          } else if (warehouse[current_pos] == ".") {
            ## there is an empty space so this box part could be moved
            res <- NULL
          }
          res
        }
        block_idx <- get_block(new_pos)
        if (any(is.na(block_idx[, 1]))) {
          ## block cannot be moved b/c a wall is blocking at some point
          new_pos <- current_pos
        } else {
          block <- warehouse[block_idx]
          new_block_idx <- t(t(block_idx) + c(dir))
          warehouse[block_idx] <<- "."
          warehouse[new_block_idx] <<- block
          warehouse[new_pos] <<- "@"
          warehouse[current_pos] <<- "."
        }
      }
    }
    if (do_print) {
      msg <- paste0("Step ", i, ": ", direction)
      cat(msg, "\n")
      show_warehouse(warehouse)
    }
    i <<- i + 1
    all_warehouses <<- c(all_warehouses, list(warehouse))
    new_pos
  }
  reduce(movements, move, .init = current_pos)
  if (save_plot) {
    anim <- animate(plot_warehouse(all_warehouses, c("S", movements)), fps = 4, 
                    nframes = length(all_warehouses))
    
  } else {
    anim <- NULL
  }
  list(warehouse = warehouse, anim = anim)
}

solution2 <- enlarge_warehouse(puzzle_data$warehouse) %>% 
  push_big_boxes(puzzle_data$movements)
calculate_gps(solution2$warehouse)
## [1] 1516544

And again a small visualization: