Task 25

Thorn Thaler - <

2025-10-03

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)
  }
  n <- text_block %>% 
    extract2(2L) %>% 
    str_extract("\\d+") %>% 
    extract2(1L) %>% 
    as.integer()
  start <- text_block %>% 
     extract2(1L) %>% 
    str_remove_all("^Begin in state |\\.$") %>% 
    extract2(1L)
  blk_idx <- text_block %>% 
    str_which("^In state")
  parse_block <- function(block) {
    block_id <- str_remove_all(block[[1L]], "In state |:$") %>% 
      extract2(1L)
    ops <- str_extract_all(block[c(3:5, 7:9)], 
                           "\\d|right|left|state .") %>% 
      str_remove(fixed("state "))
    res <- list(
      list(
      c(
        list(as.integer(ops[1L])),
        if_else(ops[2L] == "right", 1L, -1L),
        ops[3]
      ),
      c(
        list(as.integer(ops[4L])),
        if_else(ops[5L] == "right", 1L, -1L),
        ops[6]  
      )
    )
    )
    names(res) <- block_id
    res
  }
  ops <- map(blk_idx, ~ parse_block(text_block[.x:(.x + 8L)])) %>% 
    flatten()
  list(ops = ops, n = n, start = start)
}

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

2 Puzzle Day 25

2.1 Part 1

2.1.1 Description

— Day 25: The Halting Problem —

Following the twisty passageways deeper and deeper into the CPU, you finally reach the core of the computer. Here, in the expansive central chamber, you find a grand apparatus that fills the entire room, suspended nanometers above your head.

You had always imagined CPUs to be noisy, chaotic places, bustling with activity. Instead, the room is quiet, motionless, and dark.

Suddenly, you and the CPU’s garbage collector startle each other. “It’s not often we get many visitors here!”, he says. You inquire about the stopped machinery.

“It stopped milliseconds ago; not sure why. I’m a garbage collector, not a doctor.” You ask what the machine is for.

“Programs these days, don’t know their origins. That’s the Turing machine! It’s what makes the whole computer work.” You try to explain that Turing machines are merely models of computation, but he cuts you off. “No, see, that’s just what they want you to think. Ultimately, inside every CPU, there’s a Turing machine driving the whole thing! Too bad this one’s broken. We’re doomed!

You ask how you can help. “Well, unfortunately, the only way to get the computer running again would be to create a whole new Turing machine from scratch, but there’s no way you can-” He notices the look on your face, gives you a curious glance, shrugs, and goes back to sweeping the floor.

You find the Turing machine blueprints (your puzzle input) on a tablet in a nearby pile of debris. Looking back up at the broken Turing machine above, you can start to identify its parts:

  • A tape which contains 0 repeated infinitely to the left and right.
  • A cursor, which can move left or right along the tape and read or write values at its current position.
  • A set of states, each containing rules about what to do based on the current value under the cursor.

Each slot on the tape has two possible values: 0 (the starting value for all slots) and 1. Based on whether the cursor is pointing at a 0 or a 1, the current state says what value to write at the current position of the cursor, whether to move the cursor left or right one slot, and which state to use next.

For example, suppose you found the following blueprint:

Begin in state A.
Perform a diagnostic checksum after 6 steps.

In state A:
  If the current value is 0:
    - Write the value 1.
    - Move one slot to the right.
    - Continue with state B.
  If the current value is 1:
    - Write the value 0.
    - Move one slot to the left.
    - Continue with state B.

In state B:
  If the current value is 0:
    - Write the value 1.
    - Move one slot to the left.
    - Continue with state A.
  If the current value is 1:
    - Write the value 1.
    - Move one slot to the right.
    - Continue with state A.

Running it until the number of steps required to take the listed diagnostic checksum would result in the following tape configurations (with the cursor marked in square brackets):

... 0  0  0 [0] 0  0 ... (before any steps; about to run state A)
... 0  0  0  1 [0] 0 ... (after 1 step;     about to run state B)
... 0  0  0 [1] 1  0 ... (after 2 steps;    about to run state A)
... 0  0 [0] 0  1  0 ... (after 3 steps;    about to run state B)
... 0 [0] 1  0  1  0 ... (after 4 steps;    about to run state A)
... 0  1 [1] 0  1  0 ... (after 5 steps;    about to run state B)
... 0  1  1 [0] 1  0 ... (after 6 steps;    about to run state A)

The CPU can confirm that the Turing machine is working by taking a diagnostic checksum after a specific number of steps (given in the blueprint). Once the specified number of steps have been executed, the Turing machine should pause; once it does, count the number of times 1 appears on the tape. In the above example, the diagnostic checksum is 3.

Recreate the Turing machine and save the computer! What is the diagnostic checksum it produces once it’s working again?

2.1.2 Solution

Given the large repetition count, we go for a C++ solution. We ust a std::list as it allows for conveniently moving forward and backward. New items are anyways just added at either side of the list. The trickiest part was thus, just to find a proper data structure for encoding this puzzle’s data.

#ifndef STANDALONE
#include <Rcpp.h>
using namespace Rcpp;
#else
#include <iostream>
#endif
#include <array>
#include <list>
#include <numeric>
#include <unordered_map>

struct Instruction {
    int val;
    int dir;
    char state;
};

int turing(int n,
           char start,
           const std::unordered_map<char, std::pair<Instruction, Instruction>>& ops) {
  std::list<int> bits = {0};
  auto it = bits.begin();
  char state = start;

  auto move_right = [&]() {
    ++it;
    if (it == bits.end()) {
      bits.push_back(0);
      it = std::prev(bits.end());
    }
  };

  auto move_left = [&]() {
    if (it == bits.begin()) {
      bits.push_front(0);
    }
    --it;
  };

  for (int i = 0; i < n; ++i) {
    int bit = *it;
    const auto& op = ops.at(state);
    const Instruction& ins = (bit == 0) ? op.first : op.second;

    *it = ins.val;
    if (ins.dir == 1) {
      move_right();
    } else {
      move_left();
    }
    state = ins.state;
  }

  return std::accumulate(bits.begin(), bits.end(), 0);
}

#ifndef STANDALONE
Instruction make_instruction(const List& part) {
  int val = as<int>(part[0]);
  int dir = as<int>(part[1]);
  std::string state = as<std::string>(part[2]);
  char state_c = state[0];
  return Instruction {val, dir, state_c};
}

// [[Rcpp::export]]
int turing(int n, char start, const List& lops) {
  std::unordered_map<char, std::pair<Instruction, Instruction>> ops;
  CharacterVector names = lops.names();
  for (int i = 0; i < lops.size(); ++i) {
    char name_c = as<std::string>(names[i])[0];
    List inner = lops[i];
    Instruction i1 = make_instruction(inner[0]);
    Instruction i2 = make_instruction(inner[1]);
    ops[name_c] = {i1, i2};
  }
  return turing(n, start, ops);
}

#else
int main() {
  Instruction iA1 = {1, 1, 'B'};
  Instruction iA2 = {0, -1, 'B'};
  Instruction iB1 = {1, -1, 'A'};
  Instruction iB2 = {1, 1, 'A'};
  std::unordered_map<char, std::pair<Instruction, Instruction>> ops {{'A', {iA1, iA2}},
                                                                     {'B', {iB1, iB2}}};
  std::cout << turing(6, 'A', ops) << std::endl;
  return 0;
}
#endif
turing(puzzle_data$n, puzzle_data$start, puzzle_data$ops)
## [1] 633

2.2 Part 2

2.2.1 Description

— Part Two —

The Turing machine, and soon the entire computer, springs back to life. A console glows dimly nearby, awaiting your command.

> reboot printer
Error: That command requires priority 50. You currently have priority 0.
You must deposit 50 stars to increase your priority to the required level.

The console flickers for a moment, and then prints another message:

Star accepted.
You must deposit 49 stars to increase your priority to the required level.

The garbage collector winks at you, then continues sweeping.

2.2.2 Solution

Hohoho, that’s it for 2017!