diff --git a/2019/input/day2.txt b/2019/input/day2.txt new file mode 100644 index 0000000..32f1f63 --- /dev/null +++ b/2019/input/day2.txt @@ -0,0 +1 @@ +1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,10,1,19,1,19,9,23,1,23,6,27,1,9,27,31,1,31,10,35,2,13,35,39,1,39,10,43,1,43,9,47,1,47,13,51,1,51,13,55,2,55,6,59,1,59,5,63,2,10,63,67,1,67,9,71,1,71,13,75,1,6,75,79,1,10,79,83,2,9,83,87,1,87,5,91,2,91,9,95,1,6,95,99,1,99,5,103,2,103,10,107,1,107,6,111,2,9,111,115,2,9,115,119,2,13,119,123,1,123,9,127,1,5,127,131,1,131,2,135,1,135,6,0,99,2,0,14,0 diff --git a/2019/src/bin/day2.rs b/2019/src/bin/day2.rs new file mode 100644 index 0000000..5b88abb --- /dev/null +++ b/2019/src/bin/day2.rs @@ -0,0 +1,63 @@ +use std::{fs, io}; + +use advent_of_code::input; + +fn main() -> io::Result<()> { + let input = fs::read_to_string("input/day2.txt")?; + let mut program = input::read_separated_line(',', &input)?; + + // To do this, before running the program, replace position 1 with the value 12 and replace + // position 2 with the value 2. What value is left at position 0 after the program halts? + program[1] = 12; + program[2] = 2; + run_program(&mut program); + + println!("Part 1: {}", program[0]); + + Ok(()) +} + +fn run_program(program: &mut [i32]) { + let mut addr = 0; + + loop { + match program[addr] { + 1 => { + program[program[addr + 3] as usize] = + program[program[addr + 1] as usize] + program[program[addr + 2] as usize] + } + 2 => { + program[program[addr + 3] as usize] = + program[program[addr + 1] as usize] * program[program[addr + 2] as usize] + } + 99 => break, + opcode => panic!("Invalid opcode {}", opcode), + } + + addr += 4; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_example1() { + let input = "1,0,0,0,99"; + let mut program = input::read_separated_line(',', &input).unwrap(); + + run_program(&mut program); + + assert_eq!(program, &[2, 0, 0, 0, 99]) + } + #[test] + fn test_example4() { + let input = "1,1,1,4,99,5,6,0,99"; + let mut program = input::read_separated_line(',', &input).unwrap(); + + run_program(&mut program); + + assert_eq!(program, &[30, 1, 1, 4, 2, 5, 6, 0, 99]) + } +} diff --git a/2019/src/input.rs b/2019/src/input.rs index 31a06e6..f59098b 100644 --- a/2019/src/input.rs +++ b/2019/src/input.rs @@ -17,3 +17,14 @@ pub fn read_number_list>(path: P) -> io::Result> { Ok(output) } + +pub fn read_separated_line(sep: char, line: &str) -> io::Result> { + line.trim() + .split(sep) + .map(|number| { + number + .parse() + .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err)) + }) + .collect() +}