1 Setup
1.1 Libraries
library(httr)
library(xml2)
library(magrittr)
library(dplyr)
library(purrr)
library(stringr)
library(rlang)
library(bit64)
library(igraph)
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 9
2.1 Part 1
2.1.1 Description
— Day 9: Sensor Boost —
You’ve just said goodbye to the rebooted rover and left Mars when you receive a faint distress signal coming from the asteroid belt. It must be the Ceres monitoring station!
In order to lock on to the signal, you’ll need to boost your sensors. The Elves send up the latest BOOST program - Basic Operation Of System Test.
While BOOST (your puzzle input) is capable of boosting your sensors, for tenuous safety reasons, it refuses to do so until the computer it runs on passes some checks to demonstrate it is a complete Intcode computer.
Your existing Intcode computer is missing one key feature: it needs support for parameters in relative mode.
Parameters in mode 2, relative mode, behave very similarly to parameters in position mode: the parameter is interpreted as a position. Like position mode, parameters in relative mode can be read from or written to.
The important difference is that relative mode parameters don’t count from address 0. Instead, they count from a value called the relative base. The relative base starts at 0.
The address a relative mode parameter refers to is itself plus the current relative base. When the relative base is 0, relative mode parameters and position mode parameters with the same value refer to the same address.
For example, given a relative base of 50, a relative mode parameter of -7 refers to memory address 50 + -7 = 43.
The relative base is modified with the relative base offset instruction:
-
Opcode
9adjusts the relative base by the value of its only parameter. The relative base increases (or decreases, if the value is negative) by the value of the parameter.
For example, if the relative base is 2000, then after the instruction 109,19, the relative base would be 2019. If the next instruction were 204,-34, then the value at address 1985 would be output.
Your Intcode computer will also need a few other capabilities:
-
The computer’s available memory should be much larger than the initial program. Memory beyond the initial program starts with the value
0and can be read or written like any other memory. (It is invalid to try to access memory at a negative address, though.) - The computer should have support for large numbers. Some instructions near the beginning of the BOOST program will verify this capability.
Here are some example programs that use these features:
-
109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99takes no input and produces a copy of itself as output. -
1102,34915192,34915192,7,4,7,99,0should output a 16-digit number. -
104,1125899906842624,99should output the large number in the middle.
The BOOST program will ask for a single input; run it in test mode by providing it the value 1. It will perform a series of checks on each opcode, output any opcodes (and the associated parameter modes) that seem to be functioning incorrectly, and finally output a BOOST keycode.
Once your Intcode computer is fully functional, the BOOST program should report no malfunctioning opcodes when run in test mode; it should only output a single value, the BOOST keycode. What BOOST keycode does it produce?
2.1.2 Solution
We further improve our parser from Day 7 @ 2019 and adapt it to use relative parameter mode and implement opcode 9.
split_digits <- function(n) {
i <- floor(log10(n)) + 1L
digits <- integer64(i)
while (n > 0) {
digits[i] <- n %% 10L
n <- n %/% 10L
i <- i - 1L
}
digits
}
get_op <- function(op_code) {
digits <- split_digits(op_code)
n <- length(digits)
digits <- tail(c(rep(as.integer64(0L), 5L), digits), 5L)
list(op = as.integer(sum(digits[5:4] * 10L ^ (0:1))),
modes = digits[3:1])
}
parse_op_codes <- function(input, op_codes = puzzle_data,
ip = 1L,
rel_base = as.integer64(0L),
verbose = FALSE) {
out_buffer <- integer64(0L)
get_val <- function(..., modes) {
args <- enquos(...)
nms <- vapply(args, quo_name, character(1L))
args <- list(...)
modes <- modes[seq_along(args)]
res <- map2(args, modes, \(var, mod) {
if (mod == 0L) {
if ((var + 1L) > length(op_codes)) {
enlarge(var + 1L)
}
op_codes[as.integer(var + 1L)]
} else if (mod == 1L) {
var
} else if (mod == 2L) {
if ((rel_base + var + 1L) > length(op_codes)) {
enlarge(rel_base + var + 1L)
}
op_codes[as.integer(rel_base + var + 1L)]
}
}) %>%
set_names(nms)
res
}
get_addr <- function(res, mode) {
if (mode == 0L) {
if (res == 65) browser()
as.integer(res)
} else if (mode == 2L) {
if ((rel_base + res) == 65) browser()
as.integer(rel_base + res)
} else {
stop("unsopported mode for output")
}
}
enlarge <- function(idx) {
gap <- as.integer(idx) - length(op_codes)
if (gap > 0L) {
op_codes <<- c(op_codes, rep(as.integer64(0L), gap))
}
}
add <- function(x, y, res, modes) {
args <- get_val(x, y, modes = modes)
x <- args$x
y <- args$y
res <- get_addr(res, modes[3L])
enlarge(res + 1L)
op_codes[[res + 1L]] <<- x + y
ip <<- ip + 4L
TRUE
}
mul <- function(x, y, res, modes) {
args <- get_val(x, y, modes = modes)
x <- args$x
y <- args$y
res <- get_addr(res, modes[3L])
enlarge(res + 1L)
op_codes[[res + 1L]] <<- x * y
ip <<- ip + 4L
TRUE
}
set <- function(res, ..., modes) {
if (length(input) == 0L) {
return (FALSE)
}
res <- get_addr(res, modes[1L])
enlarge(res + 1L)
op_codes[[res + 1L]] <<- head(input, 1L)
ip <<- ip + 2L
input <<- tail(input, -1L)
TRUE
}
out <- function(x, ..., modes) {
args <- get_val(x, modes = modes)
x <- args$x
out_buffer <<- c(out_buffer, x)
if (verbose) {
cat(x, "\n")
}
ip <<- ip + 2L
TRUE
}
jnz <- function(x, y, ..., modes) {
args <- get_val(x, y, modes = modes)
x <- args$x
y <- args$y
if (x != 0L) {
ip <<- as.integer(y + 1L)
} else {
ip <<- ip + 3L
}
TRUE
}
jeqz <- function(x, y, ..., modes) {
args <- get_val(x, y, modes = modes)
x <- args$x
y <- args$y
if (x == 0L) {
ip <<- as.integer(y + 1L)
} else {
ip <<- ip + 3L
}
TRUE
}
lt <- function(x, y, res, modes) {
args <- get_val(x, y, modes = modes)
x <- args$x
y <- args$y
res <- get_addr(res, modes[3L])
enlarge(res + 1L)
op_codes[[res + 1L]] <<- (x < y)
ip <<- ip + 4L
TRUE
}
eq <- function(x, y, res, modes) {
args <- get_val(x, y, modes = modes)
x <- args$x
y <- args$y
res <- get_addr(res, modes[3L])
enlarge(res + 1L)
op_codes[[res + 1L]] <<- (x == y)
ip <<- ip + 4L
TRUE
}
rbo <- function(x, ..., modes) {
args <- get_val(x, modes = modes)
x <- args$x
rel_base <<- rel_base + x
ip <<- ip + 2L
TRUE
}
ops <- list(add, mul, set, out, jnz, jeqz, lt, eq, rbo)
n <- length(op_codes)
op <- get_op(op_codes[ip])
done <- TRUE
while(op$op %in% c(seq_along(ops), 99L)) {
args <- as.list(op_codes[seq(ip + 1L, length.out = 3L)])
cont <- do.call(ops[[op$op]], c(args, list(modes = op$modes)))
if (!cont) {
done <- FALSE
break
}
op <- get_op(op_codes[ip])
if (op$op == 99L) {
break
} else if (!op$op %in% seq_along(ops)) {
cat("Unknown op code", op$op, "\n")
}
}
out_buffer
}
parse_op_codes(1L, puzzle_data)
## integer64
## [1] 2453265701
2.2 Part 2
2.2.1 Description
— Part Two —
You now have a complete Intcode computer.
Finally, you can lock on to the Ceres distress signal! You just need to boost your sensors using the BOOST program.
The program runs in sensor boost mode by providing the input instruction the value 2. Once run, it will boost the sensors automatically, but it might take a few seconds to complete the operation on slower hardware. In sensor boost mode, the program will output a single value: the coordinates of the distress signal.
Run the BOOST program in sensor boost mode. What are the coordinates of the distress signal?
2.2.2 Solution
While the original parser works and is very R idomatic, it is awefully slow. We refactor the code to gain a significant speed gain. Additionally, we implemented the code also in C++ (in the appendix) for possible future use.
parse_op_codes_fast <- function(op_codes = as.numeric(puzzle_data), input = numeric(),
verbose = FALSE) {
ip <- 1L
rel_base <- 0L
out_buffer <- numeric(0)
out_len <- 0L
out_block <- 1024L
block_size <- 1024L
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 (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)
}
}
return(out_buffer[1:out_len])
}
parse_op_codes_fast(as.numeric(puzzle_data), 2)
## [1] 80805
3 C++ Version
#ifndef STANDALONE
#include <Rcpp.h>
using namespace Rcpp;
#else
#include <iostream>
#endif
#include <stdexcept>
#include <vector>
using Int = long long;
class IntcodeComputer {
public:
explicit IntcodeComputer(std::vector<Int> program)
: memory(std::move(program)) { }
void add_input(Int value) { input.push_back(value); }
bool has_output() const { return !output.empty(); }
Int get_output() {
Int val = output.front();
output.erase(output.begin());
return val;
}
bool step();
void run();
private:
enum class Mode { Position = 0, Immediate = 1, Relative = 2 };
enum class OpCode {
Add = 1,
Mul = 2,
Input = 3,
Output = 4,
JumpIfTrue = 5,
JumpIfFalse = 6,
LessThan = 7,
Equals = 8,
AdjustRelBase = 9,
Halt = 99
};
std::vector<Int> memory;
std::vector<Int> input;
std::vector<Int> output;
Int ip = 0;
Int rel_base = 0;
void ensure_size(size_t idx) {
if (idx >= memory.size())
memory.resize(idx + 1, 0);
}
Int get_value(Int param, Mode mode) const {
switch (mode) {
case Mode::Position:
return (param >= 0 && static_cast<size_t>(param) < memory.size()) ? memory[param] : 0;
case Mode::Immediate:
return param;
case Mode::Relative: {
Int addr = rel_base + param;
return (addr >= 0 && static_cast<size_t>(addr) < memory.size()) ? memory[addr] : 0;
}
default:
throw std::runtime_error("unknown parameter mode");
}
}
size_t get_address(Int param, Mode mode) const {
switch (mode) {
case Mode::Position:
return static_cast<size_t>(param);
case Mode::Relative:
return static_cast<size_t>(rel_base + param);
default:
throw std::runtime_error("invalid write mode");
}
}
static Mode decode_mode(Int instr) { return static_cast<Mode>(instr % 10); }
static OpCode decode_opcode(Int instr) { return static_cast<OpCode>(instr % 100); }
std::vector<Mode> get_parameter_modes(Int instr, int num_params) const {
std::vector<Mode> modes;
instr /= 100; // Remove opcode
for (int i = 0; i < num_params; ++i) {
modes.push_back(decode_mode(instr));
instr /= 10;
}
return modes;
}
};
bool IntcodeComputer::step() {
Int instr = memory.at(ip);
OpCode op = decode_opcode(instr);
std::vector<Mode> modes;
int num_params = 0;
switch (op) {
case OpCode::Add:
case OpCode::Mul:
case OpCode::LessThan:
case OpCode::Equals:
num_params = 3;
break;
case OpCode::JumpIfTrue:
case OpCode::JumpIfFalse:
num_params = 2;
break;
case OpCode::Input:
case OpCode::Output:
case OpCode::AdjustRelBase:
num_params = 1;
break;
case OpCode::Halt:
return false;
default:
throw std::runtime_error("unknown opcode");
}
modes = get_parameter_modes(instr, num_params);
switch (op) {
case OpCode::Add: {
Int a = get_value(memory[ip + 1], modes[0]);
Int b = get_value(memory[ip + 2], modes[1]);
size_t dest = get_address(memory[ip + 3], modes[2]);
ensure_size(dest);
memory[dest] = a + b;
ip += 4;
break;
}
case OpCode::Mul: {
Int a = get_value(memory[ip + 1], modes[0]);
Int b = get_value(memory[ip + 2], modes[1]);
size_t dest = get_address(memory[ip + 3], modes[2]);
ensure_size(dest);
memory[dest] = a * b;
ip += 4;
break;
}
case OpCode::Input: {
if (input.empty())
return false;
size_t dest = get_address(memory[ip + 1], modes[0]);
ensure_size(dest);
memory[dest] = input.front();
input.erase(input.begin());
ip += 2;
break;
}
case OpCode::Output: {
Int val = get_value(memory[ip + 1], modes[0]);
output.push_back(val);
ip += 2;
break;
}
case OpCode::JumpIfTrue: {
Int a = get_value(memory[ip + 1], modes[0]);
Int b = get_value(memory[ip + 2], modes[1]);
ip = (a != 0) ? b : ip + 3;
break;
}
case OpCode::JumpIfFalse: {
Int a = get_value(memory[ip + 1], modes[0]);
Int b = get_value(memory[ip + 2], modes[1]);
ip = (a == 0) ? b : ip + 3;
break;
}
case OpCode::LessThan: {
Int a = get_value(memory[ip + 1], modes[0]);
Int b = get_value(memory[ip + 2], modes[1]);
size_t dest = get_address(memory[ip + 3], modes[2]);
ensure_size(dest);
memory[dest] = (a < b) ? 1 : 0;
ip += 4;
break;
}
case OpCode::Equals: {
Int a = get_value(memory[ip + 1], modes[0]);
Int b = get_value(memory[ip + 2], modes[1]);
size_t dest = get_address(memory[ip + 3], modes[2]);
ensure_size(dest);
memory[dest] = (a == b) ? 1 : 0;
ip += 4;
break;
}
case OpCode::AdjustRelBase: {
Int a = get_value(memory[ip + 1], modes[0]);
rel_base += a;
ip += 2;
break;
}
case OpCode::Halt:
return false;
}
return true;
}
void IntcodeComputer::run() {
while (step()) {
// runs until input block or HALT
}
}
#ifndef STANDALONE
// [[Rcpp::export]]
IntegerVector run_intcode(IntegerVector program, IntegerVector input) {
IntcodeComputer vm(as<std::vector<Int>>(program));
for (Int val : input) {
vm.add_input(val);
}
vm.run();
std::vector<Int> output;
while (vm.has_output()) {
output.push_back(vm.get_output());
}
return wrap(output);
}
#else
int main() {
std::vector<Int> program = {
109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99};
IntcodeComputer vm(program);
vm.add_input(2);
vm.run();
while (vm.has_output()) {
std::cout << vm.get_output() << " ";
}
std::cout << "\n";
return 0;
}
#endif