1use crate::util::iter::*;
15use crate::util::parse::*;
16
17pub enum Instruction {
18 Acc(isize),
19 Jmp(isize),
20 Nop(isize),
21}
22
23impl Instruction {
24 fn new([a, b]: [&str; 2]) -> Self {
25 let amount = b.signed();
26 match a {
27 "acc" => Self::Acc(amount),
28 "jmp" => Self::Jmp(amount),
29 "nop" => Self::Nop(amount),
30 _ => unreachable!(),
31 }
32 }
33}
34
35enum State {
36 Infinite(isize),
37 Halted(isize),
38}
39
40pub fn parse(input: &str) -> Vec<Instruction> {
41 input.split_ascii_whitespace().chunk::<2>().map(Instruction::new).collect()
42}
43
44pub fn part1(input: &[Instruction]) -> isize {
45 let mut seen = vec![false; input.len()];
46
47 let State::Infinite(acc) = execute(input, 0, 0, &mut seen) else { unreachable!() };
48 acc
49}
50
51pub fn part2(input: &[Instruction]) -> isize {
52 let mut pc = 0;
53 let mut acc = 0;
54 let mut seen = vec![false; input.len()];
55
56 loop {
57 let (next, speculative) = match input[pc] {
58 Instruction::Acc(arg) => {
59 pc += 1;
60 acc += arg;
61 continue;
62 }
63 Instruction::Jmp(arg) => (pc.wrapping_add_signed(arg), pc + 1),
64 Instruction::Nop(arg) => (pc + 1, pc.wrapping_add_signed(arg)),
65 };
66
67 match execute(input, speculative, acc, &mut seen) {
68 State::Infinite(_) => pc = next,
69 State::Halted(acc) => break acc,
70 }
71 }
72}
73
74fn execute(input: &[Instruction], mut pc: usize, mut acc: isize, seen: &mut [bool]) -> State {
75 loop {
76 if pc >= input.len() {
77 break State::Halted(acc);
78 } else if seen[pc] {
79 break State::Infinite(acc);
80 }
81
82 seen[pc] = true;
83
84 match input[pc] {
85 Instruction::Acc(arg) => {
86 pc += 1;
87 acc += arg;
88 }
89 Instruction::Jmp(arg) => pc = pc.wrapping_add_signed(arg),
90 Instruction::Nop(_) => pc += 1,
91 }
92 }
93}