AoC 2019 D5: Sunny with a Chance of Asteroids

C++ | Problem statement | Source code | Tags: Intcode

← Previous Back to AoC Index Next →

The Intcode itself is relatively straightforward, but I spent some time ironing out the infrastructure for code sharing, especially since it's a bit tricky in C++.

At this point, my code is still functional. My intcode.hpp file contains two functions:

std::vector<int> parse_prog(const std::string &line);
std::vector<int> run_prog(std::vector<int> &codes, std::vector<int> inputs);
cpp

It modifies the codes vector in place, and returns a vector of outputs. The inputs are provided as a vector as well, and consumed in order.

The new main loop looks like this:

int input_idx = 0;
std::vector<int> outputs;
for (int ip = 0; codes[ip] != 99;) {
Inst inst = parse_inst(codes, ip);
switch (inst.opcode) {
case 1:
case 2:
case 7:
case 8: {
int val1 = eval_param(codes, inst.params[0]);
int val2 = eval_param(codes, inst.params[1]);
// int res = ...;
write_to(codes, inst.params[2], res);
ip += num_params_for_opcode(inst.opcode) + 1;
break;
}
case 3: {
write_to(codes, inst.params[0], inputs[input_idx]);
input_idx++;
ip += num_params_for_opcode(inst.opcode) + 1;
break;
}
case 4: {
int val = eval_param(codes, inst.params[0]);
outputs.push_back(val);
ip += num_params_for_opcode(inst.opcode) + 1;
break;
}
case 5:
case 6: {
int val = eval_param(codes, inst.params[0]);
bool should_jump = inst.opcode == 5 ? (val != 0) : (val == 0);
if (should_jump) {
ip = eval_param(codes, inst.params[1]);
} else {
ip += num_params_for_opcode(inst.opcode) + 1;
}
break;
}
default:
throw std::invalid_argument("Unknown opcode");
}
}
cpp

← Previous Back to AoC Index Next →