Task 11

Thorn Thaler - <

2025-11-24

1 Setup

1.1 Libraries

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

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(c, .) %>% 
    as.integer64()
}

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

2 Puzzle Day 11

2.1 Part 1

2.1.1 Description

— Day 11: Space Police —

On the way to Jupiter, you’re pulled over by the Space Police.

“Attention, unmarked spacecraft! You are in violation of Space Law! All spacecraft must have a clearly visible registration identifier! You have 24 hours to comply or be sent to Space Jail!”

Not wanting to be sent to Space Jail, you radio back to the Elves on Earth for help. Although it takes almost three hours for their reply signal to reach you, they send instructions for how to power up the emergency hull painting robot and even provide a small Intcode program (your puzzle input) that will cause it to paint your ship appropriately.

There’s just one problem: you don’t have an emergency hull painting robot.

You’ll need to build a new emergency hull painting robot. The robot needs to be able to move around on the grid of square panels on the side of your ship, detect the color of its current panel, and paint its current panel black or white. (All of the panels are currently black.)

The Intcode program will serve as the brain of the robot. The program uses input instructions to access the robot’s camera: provide 0 if the robot is over a black panel or 1 if the robot is over a white panel. Then, the program will output two values:

  • First, it will output a value indicating the color to paint the panel the robot is over: 0 means to paint the panel black, and 1 means to paint the panel white.
  • Second, it will output a value indicating the direction the robot should turn: 0 means it should turn left 90 degrees, and 1 means it should turn right 90 degrees.

After the robot turns, it should always move forward exactly one panel. The robot starts facing up.

The robot will continue running for a while like this and halt when it is finished drawing. Do not restart the Intcode computer inside the robot during this process.

For example, suppose the robot is about to start running. Drawing black panels as ., white panels as #, and the robot pointing the direction it is facing (< ^ > v), the initial state and region near the robot looks like this:

.....
.....
..^..
.....
.....

The panel under the robot (not visible here because a ^ is shown instead) is also black, and so any input instructions at this point should be provided 0. Suppose the robot eventually outputs 1 (paint white) and then 0 (turn left). After taking these actions and moving forward one panel, the region now looks like this:

.....
.....
.<#..
.....
.....

Input instructions should still be provided 0. Next, the robot might output 0 (paint black) and then 0 (turn left):

.....
.....
..#..
.v...
.....

After more outputs (1,0, 1,0):

.....
.....
..^..
.##..
.....

The robot is now back where it started, but because it is now on a white panel, input instructions should be provided 1. After several more outputs (0,1, 1,0, 1,0), the area looks like this:

.....
..<#.
...#.
.##..
.....

Before you deploy the robot, you should probably have an estimate of the area it will cover: specifically, you need to know the number of panels it paints at least once, regardless of color. In the example above, the robot painted 6 panels at least once. (It painted its starting panel twice, but that panel is still only counted once; it also never painted the panel it ended on.)

Build a new emergency hull painting robot and run the Intcode program on it. How many panels does it paint at least once?

2.1.2 Solution

We re-use the fast parser from Day 9 @ 2019 and feed it the int code.

parse_op_codes_fast <- function(op_codes = as.numeric(puzzle_data), input = numeric(), 
                                start_col = 0L,
                                verbose = FALSE) {
  ip <- 1L
  rel_base <- 0L
  out_buffer <- numeric(0)
  out_len <- 0L
  out_block <- 1024L
  block_size <- 1024L  # size of memory
  hash <- new.env(parent = emptyenv())
  pos <- c(x = 0L, y = 0L, dir = 0L)
  get_key <- function(pos) {
    sprintf("%s,%s", pos[1L], pos[2L])
  }
  hash[[get_key(pos)]] <- start_col
  grow_memory <- function(idx) {
    if (idx > length(op_codes)) {
      new_size <- ceiling(idx / block_size) * block_size
      op_codes <<- c(op_codes, rep(0, new_size - length(op_codes)))
    }
  }
  
  append_out <- function(val) {
    if (out_len + 1L > length(out_buffer)) {
      new_size <- length(out_buffer) + out_block
      out_buffer <<- c(out_buffer, rep(0, new_size - length(out_buffer)))
    }
    out_len <<- out_len + 1L
    out_buffer[out_len] <<- val
  }
  
  get_val <- function(param, mode) {
    if (mode == 0L) {
      grow_memory(param + 1L)
      return(op_codes[param + 1L])
    } else if (mode == 1L) {
      return(param)
    } else if (mode == 2L) {
      idx <- rel_base + param + 1L
      grow_memory(idx)
      return(op_codes[idx])
    } else {
      stop("unknown mode")
    }
  }
  
  get_addr <- function(param, mode) {
    if (mode == 0L) {
      return(param + 1L)
    } else if (mode == 2L) {
      return(rel_base + param + 1L)
    } else {
      stop("invalid write mode")
    }
  }
  
  halt <- FALSE
  while (!halt) {
    instr <- op_codes[ip]
    op <- instr %% 100L
    modes <- c(
      (instr %/% 100L) %% 10L, 
      (instr %/% 1000L) %% 10L, 
      (instr %/% 10000L) %% 10L
    )
    
    if (op == 1L) { # add
      a <- get_val(op_codes[ip + 1L], modes[1])
      b <- get_val(op_codes[ip + 2L], modes[2])
      addr <- get_addr(op_codes[ip + 3L], modes[3])
      grow_memory(addr)
      op_codes[addr] <- a + b
      ip <- ip + 4L
    } else if (op == 2L) { # mul
      a <- get_val(op_codes[ip + 1L], modes[1])
      b <- get_val(op_codes[ip + 2L], modes[2])
      addr <- get_addr(op_codes[ip + 3L], modes[3])
      grow_memory(addr)
      op_codes[addr] <- a * b
      ip <- ip + 4L
    } else if (op == 3L) { # input
      if (length(input) == 0L) {
        stop("No input available")
      }
      addr <- get_addr(op_codes[ip + 1L], modes[1])
      grow_memory(addr)
      op_codes[addr] <- input[1L]
      input <- input[-1]
      ip <- ip + 2L
    } else if (op == 4L) { # output
      val <- get_val(op_codes[ip + 1L], modes[1])
      append_out(val)
      if (out_len %% 2L == 1L) {
        # first instruction is paint
        key <- get_key(pos)
        hash[[key]] <- val
      } else {
        # second instruction is move
        pos["dir"] <- (pos["dir"] + if_else(val == 0L, -1L, 1L)) %% 4L
        if (pos["dir"] == 0L) {
          ## up
          pos["y"] <- pos["y"] - 1L
        } else if (pos["dir"] == 1L) {
          ## right
          pos["x"] <- pos["x"] + 1L
        } else if (pos["dir"] == 2L) {
          ## down
          pos["y"] <- pos["y"] + 1L
        } else {
          ## left
          pos["x"] <- pos["x"] - 1L
        }
        key <- get_key(pos)
        if (!exists(key, hash)) {
          input <- 0L
        } else {
          input <- hash[[key]]
        }
      }
      if (verbose) cat(val, "\n")
      ip <- ip + 2L
    } else if (op == 5L) { # jump-if-true
      a <- get_val(op_codes[ip + 1L], modes[1])
      b <- get_val(op_codes[ip + 2L], modes[2])
      if (a != 0L) {
        ip <- b + 1L
      } else {
        ip <- ip + 3L
      }
    } else if (op == 6L) { # jump-if-false
      a <- get_val(op_codes[ip + 1L], modes[1])
      b <- get_val(op_codes[ip + 2L], modes[2])
      if (a == 0L) {
        ip <- b + 1L
      } else {
        ip <- ip + 3L
      }
    } else if (op == 7L) { # less than
      a <- get_val(op_codes[ip + 1L], modes[1])
      b <- get_val(op_codes[ip + 2L], modes[2])
      addr <- get_addr(op_codes[ip + 3L], modes[3])
      grow_memory(addr)
      op_codes[addr] <- as.numeric(a < b)
      ip <- ip + 4L
    } else if (op == 8L) { # equals
      a <- get_val(op_codes[ip + 1L], modes[1])
      b <- get_val(op_codes[ip + 2L], modes[2])
      addr <- get_addr(op_codes[ip + 3L], modes[3])
      grow_memory(addr)
      op_codes[addr] <- as.numeric(a == b)
      ip <- ip + 4L
    } else if (op == 9L) { # adjust relative base
      a <- get_val(op_codes[ip + 1L], modes[1])
      rel_base <- rel_base + a
      ip <- ip + 2L
    } else if (op == 99L) { # halt
      halt <- TRUE
    } else {
      stop("Unknown opcode ", op)
    }
  }
  fields <- ls(hash)
  coords <- fields %>% 
    str_split(",") %>% 
    do.call(rbind, .)
  storage.mode(coords) <- "integer"
  coords <- cbind(coords, unlist(mget(fields, hash)))
  coords
}
coords <- parse_op_codes_fast(as.numeric(puzzle_data), 0L)
nrow(coords)
## [1] 1732

2.2 Part 2

2.2.1 Description

— Part Two —

You’re not sure what it’s trying to paint, but it’s definitely not a registration identifier. The Space Police are getting impatient.

Checking your external ship cameras again, you notice a white panel marked “emergency hull painting robot starting panel”. The rest of the panels are still black, but it looks like the robot was expecting to start on a white panel, not a black one.

Based on the Space Law Space Brochure that the Space Police attached to one of your windows, a valid registration identifier is always eight capital letters. After starting the robot on a single white panel instead, what registration identifier does it paint on your hull?

2.2.2 Solution

For the second part, we costruct the picture from the single pixels.

get_registration <- function(op_codes = as.numeric(puzzle_data)) {
  final_coords <-  parse_op_codes_fast(op_codes, 1L)
  deltas <- 2 - apply(final_coords, 2L, min)
  deltas[3L] <- 0L
  final_coords <- sweep(final_coords, 2, deltas, `+`)
  dd <- apply(final_coords, 2L, max)
  grid <- matrix(" ", dd[2L] + 1L, dd[1L])
  grid[final_coords[, 2:1]] <- if_else(final_coords[, 3] == 1L, "\U2588", " ")
  apply(grid, 1, paste, collapse = "") %>% 
    paste(collapse = "\n") %>% 
    cat()
  invisible(coords)
}

get_registration(as.numeric(puzzle_data)) ## ABCLFUHJ
                                            
   ██  ███   ██  █    ████ █  █ █  █   ██   
  █  █ █  █ █  █ █    █    █  █ █  █    █   
  █  █ ███  █    █    ███  █  █ ████    █   
  ████ █  █ █    █    █    █  █ █  █    █   
  █  █ █  █ █  █ █    █    █  █ █  █ █  █   
  █  █ ███   ██  ████ █     ██  █  █  ██