2020: day08: refacto before part 2

This commit is contained in:
Antoine Martin 2020-12-08 16:39:31 +01:00
parent 71a100179e
commit bdef7fcbe4

View file

@ -21,17 +21,10 @@ fn part1(input: &str) -> aoc::Result<i64> {
let mut interpreter = Interpreter::new(instructions);
let mut set = HashSet::new();
loop {
if !set.insert(interpreter.idx) {
break;
}
interpreter.step();
}
Ok(interpreter.accumulator)
Ok(match interpreter.run() {
ExitStatus::InfiniteLoop(value) => value,
ExitStatus::End(_) => return Err(err!("interpreter doesn't have an infinite loop")),
})
}
struct Interpreter {
@ -40,6 +33,11 @@ struct Interpreter {
memory: Vec<Instruction>,
}
enum ExitStatus {
InfiniteLoop(i64),
End(i64),
}
impl Interpreter {
fn new(instructions: Vec<Instruction>) -> Self {
Self {
@ -59,6 +57,20 @@ impl Interpreter {
Instruction::Nop => self.idx += 1,
}
}
fn run(&mut self) -> ExitStatus {
let mut set = HashSet::new();
while self.idx < self.memory.len() {
if !set.insert(self.idx) {
return ExitStatus::InfiniteLoop(self.accumulator);
}
self.step();
}
return ExitStatus::End(self.accumulator);
}
}
enum Instruction {