Skip to content

Instantly share code, notes, and snippets.

@moonheart08
Created December 2, 2019 20:12
Show Gist options
  • Save moonheart08/2e9919c57ff6a8f3e63a27d04ed76635 to your computer and use it in GitHub Desktop.
Save moonheart08/2e9919c57ff6a8f3e63a27d04ed76635 to your computer and use it in GitHub Desktop.
Solution to AoC day 2
pub type IntcodeNum = usize; // assume unsigned until told otherwise
pub struct IntcodeMachine {
instr_ptr: IntcodeNum,
memory: Vec<IntcodeNum>,
initial: Vec<IntcodeNum>,
}
pub struct IntcodePatch(IntcodeNum, IntcodeNum); // offset, val
impl IntcodeMachine {
pub fn new(instr_ptr: IntcodeNum, init_program: &[IntcodeNum]) -> IntcodeMachine {
IntcodeMachine {
instr_ptr,
memory: init_program.into(),
initial: init_program.into(),
}
}
pub fn patch_mem(&mut self, p: Vec<IntcodePatch>) {
for i in p {
self.write(i.0, i.1);
}
}
pub fn quick_patch(&mut self, mut offs: IntcodeNum, vals: &[IntcodeNum]) {
for i in vals {
self.write(offs, *i);
offs += 1;
}
}
pub fn reset(&mut self) {
self.instr_ptr = 0;
self.memory = self.initial.clone();
}
pub fn get_mem(&self) -> &Vec<IntcodeNum> {
&self.memory
}
pub fn read(&self, addr: IntcodeNum) -> IntcodeNum {
if let Some(v) = self.memory.get(addr) {
*v
} else {
0
}
}
pub fn read_indr(&self, addr: IntcodeNum) -> IntcodeNum {
self.read(self.read(addr))
}
pub fn write(&mut self, addr: IntcodeNum, val: IntcodeNum) {
self.memory[addr] = val;
}
pub fn tick(&mut self) -> bool /* halted? */ {
let instr = self.read(self.instr_ptr);
match instr {
1 => {
let a = self.read_indr(self.instr_ptr+1);
let b = self.read_indr(self.instr_ptr+2);
let c = self.read(self.instr_ptr+3);
self.write(c, a + b);
self.instr_ptr += 4;
false
}
2 => {
let a = self.read_indr(self.instr_ptr+1);
let b = self.read_indr(self.instr_ptr+2);
let c = self.read(self.instr_ptr+3);
self.write(c, a * b);
self.instr_ptr += 4;
false
}
99 => {
self.instr_ptr += 1;
true
}
_ => {
panic!("Invalid opcode");
}
}
}
pub fn run_to_end(&mut self) {
while !self.tick() {}
}
}
/// RUNNER ///
fn main() {
let mut mach = IntcodeMachine::new(0, &[1,12,2,3,1,1,2,3,1,3,4,3,1,5,0,3,2,1,13,19,2,9,19,23,1,23,6,27,1,13,27,31,1,31,10,35,1,9,35,39,1,39,9,43,2,6,43,47,1,47,5,51,2,10,51,55,1,6,55,59,2,13,59,63,2,13,63,67,1,6,67,71,1,71,5,75,2,75,6,79,1,5,79,83,1,83,6,87,2,10,87,91,1,9,91,95,1,6,95,99,1,99,6,103,2,103,9,107,2,107,10,111,1,5,111,115,1,115,6,119,2,6,119,123,1,10,123,127,1,127,5,131,1,131,2,135,1,135,5,0,99,2,0,14,0]);
let mut v = 0;
let mut n = 0;
while mach.read(0) != 19690720 {
mach.reset();
mach.quick_patch(1, &[v, n]);
mach.run_to_end();
v += 1;
if v == 100 {
v = 0;
n += 1;
}
}
println!("{}, {}", v, n);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment