From 306ac5472e7efd0557834c219e8e7811b204c01d Mon Sep 17 00:00:00 2001 From: Vladan Popovic Date: Wed, 15 Jan 2020 20:09:37 +0100 Subject: [PATCH] Overengineer the intcode computer --- src/day2.rs | 81 +++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 63 insertions(+), 18 deletions(-) diff --git a/src/day2.rs b/src/day2.rs index 8a102c6..27c50a7 100644 --- a/src/day2.rs +++ b/src/day2.rs @@ -1,25 +1,70 @@ use std; -fn compute_intcode(p: &mut Vec) -> Vec { - for idx in (0..(p.len())).step_by(4) { - match p[idx] { - 1 => { - let left = p[idx + 1]; - let right = p[idx + 2]; - let res = p[idx + 3]; - p[res] = p[left] + p[right]; - } - 2 => { - let left = p[idx + 1]; - let right = p[idx + 2]; - let res = p[idx + 3]; - p[res] = p[left] * p[right]; - } - 99 => break, - _ => panic!("Something went wrong!"), +struct Params { + op1: usize, + op2: usize, + result: usize, +} + +enum Instruction { + Add(Params), + Mul(Params), + GetParam(usize), + Start, + Halt, +} + +struct IntcodeComputer { + memory: Vec, + output: Vec, + instruction: Instruction, + ip: usize, // instruction pointer +} + +impl IntcodeComputer { + fn new(memory: Vec) -> Self { + IntcodeComputer { + memory, + output: vec![], + instruction: Instruction::Start, + ip: 0, + } + } + fn add(&mut self) { + let op = self.get_params(); + self.memory[op.result] = self.memory[op.op1] + self.memory[op.op2] + } + fn mul(&mut self) { + let op = self.get_params(); + self.memory[op.result] = self.memory[op.op1] * self.memory[op.op2] + } + fn get_params(&mut self) -> Params { + Params { + op1: self.next(), + op2: self.next(), + result: self.next(), } } - p.to_vec() + fn halt(&mut self) { + self.instruction = Instruction::Halt; + } + fn next(&mut self) -> usize { + self.ip += 1; + self.memory[self.ip] + } + fn tick(&mut self) { + match self.next() { + 1 => self.add(), + 2 => self.mul(), + 99 => self.halt(), + _ => panic!("invalid input code"), + } + } +} + +fn compute_intcode(p: &mut Vec) -> Vec { + let computer = IntcodeComputer::new(p); + while } pub fn part_one() {