year2016/
day23.rs

1use crate::assembunny::Interpreter;
2use utils::prelude::*;
3
4/// Interpreting assembunny assembly, again.
5///
6/// The key optimization is that
7/// ```text
8///  cpy $r1 $r2
9///  inc $r3
10///  dec $r2
11///  jnz $r2 -2
12///  dec $r4
13///  jnz $r4 -5
14/// ```
15/// can be replaced with `$r3 = $r1 * r3` followed by `$r2 = 0` and `$r4 = 0`. This reduces the
16/// number of simulated cycles for part 2 ~2,000,000 times when using the previously implemented
17/// addition optimization, and ~6,000,000 times compared to a naive implementation.
18///
19/// See also [2016 day 12](crate::Day12).
20#[derive(Clone, Debug)]
21pub struct Day23 {
22    interpreter: Interpreter<true, false>,
23}
24
25impl Day23 {
26    pub fn new(input: &str, _: InputType) -> Result<Self, InputError> {
27        Ok(Self {
28            interpreter: Interpreter::new(input)?,
29        })
30    }
31
32    #[must_use]
33    pub fn part1(&self) -> i32 {
34        self.interpreter.execute([7, 0, 0, 0])
35    }
36
37    #[must_use]
38    pub fn part2(&self) -> i32 {
39        self.interpreter.execute([12, 0, 0, 0])
40    }
41}
42
43examples!(Day23 -> (i32, i32) [
44    {
45        input: "cpy 2 a\n\
46            tgl a\n\
47            tgl a\n\
48            tgl a\n\
49            cpy 1 a\n\
50            dec a\n\
51            dec a",
52        part1: 3,
53    },
54]);