Intcode: add method for single step execution

This commit is contained in:
kageru 2019-12-13 10:44:13 +01:00
parent 1d164979c6
commit b3f7431be4
2 changed files with 20 additions and 7 deletions

@ -9,6 +9,7 @@ pub struct IntComputer {
pub enum IntComputerResult { pub enum IntComputerResult {
Halt, Halt,
Output(i64), Output(i64),
Continue,
} }
impl IntComputerResult { impl IntComputerResult {
@ -16,6 +17,7 @@ impl IntComputerResult {
match self { match self {
IntComputerResult::Halt => panic!("Attempted to get value of halt operation"), IntComputerResult::Halt => panic!("Attempted to get value of halt operation"),
IntComputerResult::Output(o) => o, IntComputerResult::Output(o) => o,
IntComputerResult::Continue => panic!("Attempted to get value of non-output operation"),
} }
} }
} }
@ -31,15 +33,25 @@ impl IntComputer {
} }
} }
pub fn step(&mut self) -> IntComputerResult {
match self.cmd_buffer.pop().unwrap_or_else(|| self.decode_next()) {
Operation::Halt {} => return IntComputerResult::Halt,
op => {
if let Some(o) = self.execute(op.to_owned()) {
return IntComputerResult::Output(o);
} else {
return IntComputerResult::Continue;
}
}
}
}
pub fn run(&mut self) -> IntComputerResult { pub fn run(&mut self) -> IntComputerResult {
loop { loop {
match self.cmd_buffer.pop().unwrap_or_else(|| self.decode_next()) { match self.step() {
Operation::Halt {} => return IntComputerResult::Halt, IntComputerResult::Halt => return IntComputerResult::Halt,
op => { IntComputerResult::Output(o) => return IntComputerResult::Output(o),
if let Some(o) = self.execute(op.to_owned()) { IntComputerResult::Continue => (),
return IntComputerResult::Output(o);
}
}
} }
} }
} }

@ -22,6 +22,7 @@ pub fn run_for_input(input: &Vec<i64>, acc: &mut i64, amp_phases: Vec<i64>) -> i
match amplifier.run() { match amplifier.run() {
IntComputerResult::Output(output) => *acc = output, IntComputerResult::Output(output) => *acc = output,
IntComputerResult::Halt => break, IntComputerResult::Halt => break,
IntComputerResult::Continue => unreachable!()
} }
} }
*acc *acc