Today's challenge was already much more difficult than yesterday's but it was still easy enough.
The challenge was to implement an interpreter for a machine code
called Intcode. You were given a program in form of opcodes and needed to
execute it. It was quite enjoyable and with the match
syntax of Rust
also pretty comfortable to do so.
Code
fn execute_intcode(mut program: Vec<i32>) -> i32 {
let mut ip = 0;
loop {
let out_addr = program[ip + 3] as usize;
let in_addr_1 = program[ip + 1] as usize;
let in_addr_2 = program[ip + 2] as usize;
match program[ip] {
1 => program[out_addr] = program[in_addr_1] + program[in_addr_2],
2 => program[out_addr] = program[in_addr_1] * program[in_addr_2],
99 => break,
_ => panic!("Unknown opcode: {}", program[ip]),
}
ip += 4
}
program[0]
}
pub fn part_one(input: &str) -> i32 {
let mut program = parse_input(input);
program[1] = 12;
program[2] = 2;
execute_intcode(program.clone())
}
pub fn part_two(input: &str) -> i32 {
let program = parse_input(input);
for noun in 0..99 {
for verb in 0..99 {
let mut program_clone = program.clone();
program_clone[1] = noun;
program_clone[2] = verb;
if execute_intcode(program_clone) == 19_690_720 {
return 100 * noun + verb;
}
}
}
panic!("No solution found!");
}
Benchmarks
2019 - Day 02 - Part 1 time: [5.0659 us 5.2681 us 5.4860 us]
2019 - Day 02 - Part 2 time: [1.3271 ms 1.3992 ms 1.4795 ms]
Feedback or Questions?
I don't have a direct way to leave comments on posts. But if you want to give some feedback or have some questions you can contact in other ways.