Skip to main content

aoc/year2019/
day02.rs

1//! # 1202 Program Alarm
2//!
3//! Substituting symbols instead of numbers into the program shows that it calculates the value of:
4//!
5//! `a * noun + b * verb + c`
6//!
7//! We can isolate the value of the constants a, b, c in order to speed up subsequent calculations.
8//!
9//! Since the equation is linear in noun and verb, we can efficiently solve part two by iterating
10//! over possible noun values and computing the corresponding verb directly.
11use crate::util::parse::*;
12
13type Input = [i32; 3];
14
15pub fn parse(input: &str) -> Input {
16    let code: Vec<_> = input.iter_unsigned().collect();
17    let [a, b, c] = [[1, 0], [0, 1], [0, 0]].map(|[noun, verb]| check(&code, noun, verb));
18
19    [a - c, b - c, c]
20}
21
22pub fn part1([a, b, c]: &Input) -> i32 {
23    a * 12 + b * 2 + c
24}
25
26pub fn part2([a, b, c]: &Input) -> i32 {
27    (0..100)
28        .find_map(|x| {
29            let y = (19690720 - a * x - c) / b;
30            (a * x + b * y + c == 19690720 && (0..100).contains(&y)).then_some(100 * x + y)
31        })
32        .unwrap()
33}
34
35fn check(code: &[usize], first: usize, second: usize) -> i32 {
36    let mut pc = 0;
37    let code = &mut *code.to_vec();
38
39    code[1] = first;
40    code[2] = second;
41
42    loop {
43        match code[pc] {
44            1 => code[code[pc + 3]] = code[code[pc + 1]] + code[code[pc + 2]],
45            2 => code[code[pc + 3]] = code[code[pc + 1]] * code[code[pc + 2]],
46            _ => break code[0] as i32,
47        }
48        pc += 4;
49    }
50}