year2016/
day12.rs

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