year2019/
day09.rs

1use utils::prelude::*;
2
3use crate::intcode::features::Day09Features;
4use crate::intcode::{Event, Interpreter};
5
6/// Interpreting assembly with base-relative addressing.
7#[derive(Clone, Debug)]
8pub struct Day09 {
9    interpreter: Interpreter,
10}
11
12impl Day09 {
13    pub fn new(input: &str, _: InputType) -> Result<Self, InputError> {
14        Ok(Self {
15            interpreter: Interpreter::parse(input, 1)?,
16        })
17    }
18
19    #[must_use]
20    pub fn part1(&self) -> i64 {
21        self.run(1)
22    }
23
24    #[must_use]
25    pub fn part2(&self) -> i64 {
26        self.run(2)
27    }
28
29    fn run(&self, input: i64) -> i64 {
30        let mut interpreter = self.interpreter.clone();
31        interpreter.push_input(input);
32
33        let mut output = None;
34        loop {
35            match interpreter.run::<Day09Features>() {
36                Event::Halt => {
37                    return output.expect("no solution found: program produced no output");
38                }
39                Event::Input => panic!("no solution found: program required more input"),
40                Event::Output(_) if output.is_some() => {
41                    panic!("no solution found: program output multiple values")
42                }
43                Event::Output(x) => output = Some(x),
44            }
45        }
46    }
47}
48
49examples!(Day09 -> (i64, i64) []);