-
Notifications
You must be signed in to change notification settings - Fork 0
/
day02.rs
64 lines (50 loc) · 1.81 KB
/
day02.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
use crate::intcode_computer::Computer;
use crate::parse_custom_separated;
use itertools::iproduct;
fn run_until_halt(memory: Vec<i64>) -> i64 {
let mut numbers: Vec<i64> = memory;
let mut pc = 0;
while numbers[pc] != 99 {
let x_position = numbers[pc + 1] as usize;
let y_position = numbers[pc + 2] as usize;
let z_position = numbers[pc + 3] as usize;
match numbers[pc] {
1 => {
numbers[z_position] = numbers[x_position] + numbers[y_position];
}
2 => {
numbers[z_position] = numbers[x_position] * numbers[y_position];
}
_ => panic!("Unknown opcode {}", numbers[pc]),
}
pc += 4
}
numbers[0]
}
pub fn star_one(input: &str) -> isize {
let program = parse_custom_separated::<isize>(input, ",").collect();
let mut computer = Computer::with_input(program, || Some(1));
computer.run_until_halt_or_paused(false);
computer.memory().read(0)
}
pub fn star_two(input: &str) -> isize {
let program: Vec<_> = parse_custom_separated::<isize>(input, ",").collect();
let (noun, verb) = iproduct!((0..=99), (0..=99))
.find(|&(noun, verb)| {
let mut modified_computer = Computer::with_input(program.clone(), || Some(1));
modified_computer.memory().write(1, noun);
modified_computer.memory().write(2, verb);
modified_computer.run_until_halt_or_paused(false);
modified_computer.memory().read(0) == 19690720
})
.expect("There should be a noun and verb that results in the output `19690720`");
100 * noun + verb
}
#[cfg(test)]
mod tests {
use super::{star_one, star_two};
#[test]
fn test_star_one() {
assert_eq!(star_one("1,9,10,3,2,3,11,0,99,30,40,50"), 3500);
}
}