From e8a0fa1627d1ebfae0083a86a589d71d5326ddc9 Mon Sep 17 00:00:00 2001 From: "Eric N. Vander Weele" Date: Sun, 28 Jan 2024 17:37:29 -0500 Subject: [PATCH] 2019: Day 2 --- 2019/input_02.txt | 1 + 2019/src/bin/puzzle_02.rs | 77 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 2019/input_02.txt create mode 100644 2019/src/bin/puzzle_02.rs diff --git a/2019/input_02.txt b/2019/input_02.txt new file mode 100644 index 0000000..6ffe0d5 --- /dev/null +++ b/2019/input_02.txt @@ -0,0 +1 @@ +1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,1,10,19,1,19,5,23,2,23,6,27,1,27,5,31,2,6,31,35,1,5,35,39,2,39,9,43,1,43,5,47,1,10,47,51,1,51,6,55,1,55,10,59,1,59,6,63,2,13,63,67,1,9,67,71,2,6,71,75,1,5,75,79,1,9,79,83,2,6,83,87,1,5,87,91,2,6,91,95,2,95,9,99,1,99,6,103,1,103,13,107,2,13,107,111,2,111,10,115,1,115,6,119,1,6,119,123,2,6,123,127,1,127,5,131,2,131,6,135,1,135,2,139,1,139,9,0,99,2,14,0,0 diff --git a/2019/src/bin/puzzle_02.rs b/2019/src/bin/puzzle_02.rs new file mode 100644 index 0000000..2816b10 --- /dev/null +++ b/2019/src/bin/puzzle_02.rs @@ -0,0 +1,77 @@ +use std::convert::From; +use std::io; +use std::ops; + +enum Opcode { + Add = 1, + Multiply = 2, + Halt = 99, +} + +impl From for Opcode { + fn from(x: u32) -> Self { + match x { + 1 => Opcode::Add, + 2 => Opcode::Multiply, + 99 => Opcode::Halt, + _ => unreachable!(), + } + } +} + +const INSTRUCTION_LEN: usize = 4; + +fn extract_parameters(instruction: &[u32]) -> (usize, usize, usize) { + ( + usize::try_from(instruction[1]).unwrap(), + usize::try_from(instruction[2]).unwrap(), + usize::try_from(instruction[3]).unwrap(), + ) +} + +fn run_program(prog: &[u32], addr1_val: u32, addr2_val: u32) -> Vec { + let mut prog = prog.to_vec(); + + prog[1] = addr1_val; + prog[2] = addr2_val; + + let mut idx: usize = 0; + loop { + match Opcode::from(prog[idx]) { + Opcode::Add => { + let (addr1, addr2, dst) = extract_parameters(&prog[idx..]); + prog[dst] = prog[addr1] + prog[addr2]; + } + Opcode::Multiply => { + let (addr1, addr2, dst) = extract_parameters(&prog[idx..]); + prog[dst] = prog[addr1] * prog[addr2]; + } + Opcode::Halt => break, + } + + idx += INSTRUCTION_LEN; + } + + prog +} + +fn main() { + let intcode_prog: Vec = io::read_to_string(io::stdin()) + .unwrap() + .trim() + .split(',') + .map(|x| x.parse().unwrap()) + .collect(); + + println!("Part 1: {}", run_program(&intcode_prog, 12, 2)[0]); + + const TARGET_OUTPUT: u32 = 19690720; + const INPUT_RANGE: ops::RangeInclusive = 0..=99; + + let (noun, verb) = INPUT_RANGE + .flat_map(|noun| INPUT_RANGE.map(move |verb| (noun, verb))) + .find(|&(noun, verb)| run_program(&intcode_prog, noun, verb)[0] == TARGET_OUTPUT) + .unwrap(); + + println!("Part 2: {}", 100 * noun + verb); +}