Skip to content

Commit

Permalink
2019: Day 2
Browse files Browse the repository at this point in the history
  • Loading branch information
ericvw committed Feb 7, 2024
1 parent 5d36476 commit e8a0fa1
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
1 change: 1 addition & 0 deletions 2019/input_02.txt
Original file line number Diff line number Diff line change
@@ -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
77 changes: 77 additions & 0 deletions 2019/src/bin/puzzle_02.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
use std::convert::From;
use std::io;
use std::ops;

enum Opcode {
Add = 1,
Multiply = 2,
Halt = 99,
}

impl From<u32> 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<u32> {
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<u32> = 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<u32> = 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);
}

0 comments on commit e8a0fa1

Please sign in to comment.