Task 14

Thorn Thaler - <

2026-01-07

1 Setup

1.1 Libraries

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

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)
  }
  bm <- str_which(text_block, "mask")
  end <- c(tail(bm, -1L), length(text_block) + 1L)
  map2(bm, end, function(s, e) {
    bl <- text_block[s:(e - 1L)]
    mask <- str_extract(bl[1L], "[01X]+")[[1L]]
    set_op <- str_extract_all(bl[-1L], "\\d+") %>% 
      do.call(rbind, .) %>% 
      set_colnames(c("addr", "val"))
    storage.mode(set_op) <- "integer"
    list(mask = mask, mem = set_op)
  })
}

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

2 Puzzle Day 14

2.1 Part 1

2.1.1 Description

— Day 14: Docking Data —

As your ferry approaches the sea port, the captain asks for your help again. The computer system that runs this port isn’t compatible with the docking program on the ferry, so the docking parameters aren’t being correctly initialized in the docking program’s memory.

After a brief inspection, you discover that the sea port’s computer system uses a strange bitmask system in its initialization program. Although you don’t have the correct decoder chip handy, you can emulate it in software!

The initialization program (your puzzle input) can either update the bitmask or write a value to memory. Values and memory addresses are both 36-bit unsigned integers. For example, ignoring bitmasks for a moment, a line like mem[8] = 11 would write the value 11 to memory address 8.

The bitmask is always given as a string of 36 bits, written with the most significant bit (representing 2^35) on the left and the least significant bit (2^0, that is, the 1s bit) on the right. The current bitmask is applied to values immediately before they are written to memory: a 0 or 1 overwrites the corresponding bit in the value, while an X leaves the bit in the value unchanged.

For example, consider the following program:

mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
mem[8] = 11
mem[7] = 101
mem[8] = 0

This program starts by specifying a bitmask (mask = ….). The mask it specifies will overwrite two bits in every written value: the 2s bit is overwritten with 0, and the 64s bit is overwritten with 1.

The program then attempts to write the value 11 to memory address 8. By expanding everything out to individual bits, the mask is applied as follows:

value:  000000000000000000000000000000001011  (decimal 11)
mask:   XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
result: 000000000000000000000000000001001001  (decimal 73)

So, because of the mask, the value 73 is written to memory address 8 instead. Then, the program tries to write 101 to address 7:

value:  000000000000000000000000000001100101  (decimal 101)
mask:   XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
result: 000000000000000000000000000001100101  (decimal 101)

This time, the mask has no effect, as the bits it overwrote were already the values the mask tried to set. Finally, the program tries to write 0 to address 8:

value:  000000000000000000000000000000000000  (decimal 0)
mask:   XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
result: 000000000000000000000000000001000000  (decimal 64)

64 is written to address 8 instead, overwriting the value that was there previously.

To initialize your ferry’s docking program, you need the sum of all values left in memory after the initialization program completes. (The entire 36-bit address space begins initialized to the value 0 at every address.) In the above example, only two values in memory are not zero - 101 (at address 7) and 64 (at address 8) - producing a sum of 165.

Execute the initialization program. What is the sum of all values left in memory after it completes? (Do not truncate the sum to 36 bits.)

2.1.2 Solution

To apply a bitmask we use (x & ~clear_mask) | set_mask where clear_mask contains 1 at each position where we want to set a bit to 0 and a 0 at the positions which should not be changed. Likewise set_mask contains a 1 at each position which we want to set to set to 1 and 0 otherwise.

N.B. As we need bit 64 bitwise operations, we include a simple C++ code to avoid the need to work on bit vectors in R for speed reasons.

#include <Rcpp.h>

inline bool is_integer64(SEXP x) {
  return TYPEOF(x) == REALSXP && Rf_inherits(x, "integer64");
}

inline void assert_integer64(const Rcpp::NumericVector& v, const char* argname) {
  if (!is_integer64(v)) {
    Rcpp::stop(
      "argument '%s' must be an integer64 vector", argname);
  }
}

inline void read_uint64_buffer(const Rcpp::NumericVector& src, 
                               std::vector<uint64_t>& out) {
  const std::size_t n = src.size();
  out.resize(n);
  if (n > 0) {
    std::memcpy(out.data(), REAL(src), n * sizeof(double));
  }
}

inline Rcpp::NumericVector write_uint64_buffer(const std::vector<uint64_t>& buf) {
  const std::size_t n = buf.size();
  Rcpp::NumericVector res(n);
  if (n > 0) {
    std::memcpy(REAL(res), buf.data(), n * sizeof(double));
  }
  res.attr("class") = Rcpp::CharacterVector::create("integer64");
  return res;
}

template <typename BinOp>
Rcpp::NumericVector bitwOp64(Rcpp::NumericVector a,
                             Rcpp::NumericVector b,
                             BinOp op,
                             const char* opname = "bitwOp64") {
  
  assert_integer64(a, "a");
  assert_integer64(b, "b");
  
  const std::size_t lenA = a.size();
  const std::size_t lenB = b.size();
  
  if (lenA == 0 || lenB == 0) {
    Rcpp::NumericVector res0(0);
    res0.attr("class") = Rcpp::CharacterVector::create("integer64");
    return res0;
  }
  
  const std::size_t n = (lenA > lenB) ? lenA : lenB;
  if ((n % lenA) != 0 || (n % lenB) != 0) {
    Rcpp::warning(
      "longer object length is not a multiple of shorter object length in '%s'", opname);
  }
  
  std::vector<uint64_t> X, Y;
  read_uint64_buffer(a, X);
  read_uint64_buffer(b, Y);
  
  std::vector<uint64_t> res(n);
  
  for (std::size_t i = 0; i < n; ++i) {
    const std::size_t ia = i % lenA;
    const std::size_t ib = i % lenB;
    res[i] = op(X[ia], Y[ib]);
  }
  
  return write_uint64_buffer(res);
}

template <typename UnOp>
Rcpp::NumericVector bitwOp64(Rcpp::NumericVector a,
                             UnOp op,
                             const char* opname = "bitwOp64") {
  assert_integer64(a, "a");
  const std::size_t n = a.size();
  std::vector<uint64_t> X;
  read_uint64_buffer(a, X);
  std::vector<uint64_t> res(n);
  for (std::size_t i = 0; i < n; ++i) {
    res[i] = op(X[i]);
  }
  return write_uint64_buffer(res);
}


template <typename ShiftOp>
Rcpp::NumericVector bitwShift64_impl(Rcpp::NumericVector a,
                                     Rcpp::IntegerVector shift,
                                     std::size_t nbits,
                                     ShiftOp op,
                                     const char* opname) {
  assert_integer64(a, "a");
  
  const std::size_t lenA = a.size();
  const std::size_t lenS = shift.size();
  
  if (lenA == 0 || lenS == 0) {
    Rcpp::NumericVector res0(0);
    res0.attr("class") = Rcpp::CharacterVector::create("integer64");
    return res0;
  }
  
  const std::size_t n = (lenA > lenS) ? lenA : lenS;
  if ((n % lenA) != 0 || (n % lenS) != 0) {
    Rcpp::warning("longer object length is not a multiple of shorter object length in '%s'", opname);
  }
  
  const unsigned int width = (nbits >= 64) ? 64u : static_cast<unsigned int>(nbits);
  const uint64_t mask = (width == 0) ? 0ULL
  : (width == 64 ? ~0ULL : ((1ULL << width) - 1ULL));
  
  std::vector<uint64_t> X;
  read_uint64_buffer(a, X);
  
  std::vector<uint64_t> R(n);
  
  for (std::size_t i = 0; i < n; ++i) {
    const std::size_t ia = i % lenA;
    const std::size_t is = i % lenS;
    
    int si = shift[is];
    if (si == NA_INTEGER) {
      Rcpp::stop("missing values in 'shift' are not allowed");
    }
    if (si < 0) {
      Rcpp::stop("argument 'shift' must be non-negative");
    }
    const unsigned int k = static_cast<unsigned int>(si);
    
    const uint64_t x = X[ia];
    
    R[i] = op(x, k, mask, width);
  }
  
  return write_uint64_buffer(R);
}


// [[Rcpp::export]]
Rcpp::NumericVector bitwAnd64(Rcpp::NumericVector a, Rcpp::NumericVector b) {
  return bitwOp64(a, b, [](uint64_t x, uint64_t y) { return x & y; }, "bitwAnd64");
}

// [[Rcpp::export]]
Rcpp::NumericVector bitwOr64(Rcpp::NumericVector a, Rcpp::NumericVector b) {
  return bitwOp64(a, b, [](uint64_t x, uint64_t y) { return x | y; }, "bitwOr64");
}

// [[Rcpp::export]]
Rcpp::NumericVector bitwXor64(Rcpp::NumericVector a, Rcpp::NumericVector b) {
  return bitwOp64(a, b, [](uint64_t x, uint64_t y) { return x ^ y; }, "bitwXor64");
}

// [[Rcpp::export]]
Rcpp::NumericVector bitwNot64(Rcpp::NumericVector a, std::size_t nbits = 64) {
  const uint64_t mask = (nbits == 0) ? 0ULL : 
    (nbits >= 64 ? ~0ULL : ((1ULL << nbits) - 1ULL));
  return bitwOp64(a,
                  [mask](uint64_t x) {
                    const uint64_t ux = static_cast<uint64_t>(x);
                    const uint64_t rx = (~ux) & mask;
                    return static_cast<uint64_t>(rx);
                  },
                  "bitwNot64"
  );
}

// [[Rcpp::export]]
Rcpp::NumericVector bitwShiftL64(Rcpp::NumericVector a,
                                 Rcpp::IntegerVector shift,
                                 std::size_t nbits = 64) {
  auto opL = [] (uint64_t x, unsigned int k, uint64_t mask, unsigned int width) -> uint64_t {
    if (width == 0) {
      return 0ULL;  
    }
    const uint64_t v = x & mask;
    if (k >= width) {
      return 0ULL; 
    }
    return (v << k) & mask;
  };
  return bitwShift64_impl(a, shift, nbits, opL, "bitwShiftL64");
}

// [[Rcpp::export]]
Rcpp::NumericVector bitwShiftR64(Rcpp::NumericVector a,
                                 Rcpp::IntegerVector shift,
                                 std::size_t nbits = 64) {
  auto opR = [] (uint64_t x, unsigned int k, uint64_t mask, unsigned int width) -> uint64_t {
    if (width == 0) {
      return 0ULL;  
    }
    const uint64_t v = x & mask;
    if (k >= width) {
      return 0ULL; 
    }
    return (v >> k) & mask;
  };
  return bitwShift64_impl(a, shift, nbits, opR, "bitwShiftR64");
}
bit2num <- function(x) {
  bits <- str_split(x, "") %>% 
    extract2(1L) %>% 
    as.integer()
  n <- length(bits)
  sum(2 ^ ((n - 1L):0) * bits) %>% 
    as.integer64
}

get_clear_mask <- function(mask, which = c("value", "addr")) {
  which <- match.arg(which)
  if (which == "value") {
    str_replace_all(mask, "1", "X") %>% 
      extract2(1L) %>% 
      str_replace_all("0", "1") %>% 
      extract2(1L) %>% 
      str_replace_all("X", "0") %>% 
      extract2(1L) %>% 
      bit2num()
  } else {
    str_replace_all(mask, "X", "1") %>% 
      extract2(1L) %>% 
      bit2num()
  }
}

get_set_mask <- function(mask, which = c("value", "addr")) {
  which <- match.arg(which)
  if (which == "value") {
    str_replace_all(mask, "X", "0") %>% 
      extract2(1L) %>% 
      bit2num()
  } else {
    digits <- str_split(mask, "") %>% 
      extract2(1L) %>% 
      as.list()
    digits[digits == "X"] <- list(c("0", "1"))
    do.call(expand_grid, digits) %>% 
      unite("mask", sep = "") %>% 
      rowwise() %>% 
      mutate(mask = bit2num(mask)) %>% 
      pull(mask)
  }
}

apply_mask <- function(vals, masks) {
  bitwOr64(bitwAnd64(vals, bitwNot64(masks$clear, 36L)), masks$set)
}

set_memory <- function(ops) {
  mem_size <- vapply(ops, \(.x) max(.x$mem[, "addr"]), integer(1L)) %>% 
    max()
  mem <- integer64(mem_size)
  for (op in ops) {
    masks <- list(set = get_set_mask(op$mask, "value"),
                  clear = get_clear_mask(op$mask, "value"))
    mem[op$mem[, "addr"]] <- apply_mask(as.integer64(op$mem[, "val"]), masks) 
  }
  sum(mem)
}

set_memory(puzzle_data)
## integer64
## [1] 6631883285184

2.2 Part 2

2.2.1 Description

— Part Two —

For some reason, the sea port’s computer system still can’t communicate with your ferry’s docking program. It must be using version 2 of the decoder chip!

A version 2 decoder chip doesn’t modify the values being written at all. Instead, it acts as a memory address decoder. Immediately before a value is written to memory, each bit in the bitmask modifies the corresponding bit of the destination memory address in the following way:

  • If the bitmask bit is 0, the corresponding memory address bit is unchanged.
  • If the bitmask bit is 1, the corresponding memory address bit is overwritten with 1.
  • If the bitmask bit is X, the corresponding memory address bit is floating.

A floating bit is not connected to anything and instead fluctuates unpredictably. In practice, this means the floating bits will take on all possible values, potentially causing many memory addresses to be written all at once!

For example, consider the following program:

mask = 000000000000000000000000000000X1001X
mem[42] = 100
mask = 00000000000000000000000000000000X0XX
mem[26] = 1

When this program goes to write to memory address 42, it first applies the bitmask:

address: 000000000000000000000000000000101010  (decimal 42)
mask:    000000000000000000000000000000X1001X
result:  000000000000000000000000000000X1101X

After applying the mask, four bits are overwritten, three of which are different, and two of which are floating. Floating bits take on every possible combination of values; with two floating bits, four actual memory addresses are written:

000000000000000000000000000000011010  (decimal 26)
000000000000000000000000000000011011  (decimal 27)
000000000000000000000000000000111010  (decimal 58)
000000000000000000000000000000111011  (decimal 59)

Next, the program is about to write to memory address 26 with a different bitmask:

address: 000000000000000000000000000000011010  (decimal 26)
mask:    00000000000000000000000000000000X0XX
result:  00000000000000000000000000000001X0XX

This results in an address with three floating bits, causing writes to eight memory addresses:

000000000000000000000000000000010000  (decimal 16)
000000000000000000000000000000010001  (decimal 17)
000000000000000000000000000000010010  (decimal 18)
000000000000000000000000000000010011  (decimal 19)
000000000000000000000000000000011000  (decimal 24)
000000000000000000000000000000011001  (decimal 25)
000000000000000000000000000000011010  (decimal 26)
000000000000000000000000000000011011  (decimal 27)

The entire 36-bit address space still begins initialized to the value 0 at every address, and you still need the sum of all values left in memory at the end of the program. In this example, the sum is 208.

Execute the initialization program using an emulator for a version 2 decoder chip. What is the sum of all values left in memory after it completes?

2.2.2 Solution

To deal with the floating bits for the address mask we use the following approach:

  1. We set all bits to 0 where the bitmask contains a 1 or a X. We store this operation in clear_mask
  2. Then, we generate all possible bitmasks by replacing all X by 0 and 1 and looking at all combination (set_mask)
  3. To get the final address we look at x & ~clear_mask | set_mask as before.
set_memory_floating <- function(ops) {
  mem <- NULL
  for (op in ops) {
    masks <- list(set = get_set_mask(op$mask, "addr"),
                  clear = get_clear_mask(op$mask, "addr"))
    for (i in seq_len(nrow(op$mem))) {
      addr <- apply_mask(as.integer64(op$mem[i, "addr"]), masks) %>% 
        as.character()
      mem[addr] <- as.list(as.integer64(op$mem[i, "val"]))
    }
  }
  do.call(c, mem) %>% 
    sum()
}

set_memory_floating(puzzle_data)
## integer64
## [1] 3161838538691