Browse Source

Add day2 part 1

master
parent
commit
1bfdd4dba2
  1. 1
      input/day2
  2. 69
      src/day2.rs
  3. 4
      src/main.rs

1
input/day2

@ -0,0 +1 @@
1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,6,1,19,1,5,19,23,2,6,23,27,1,27,5,31,2,9,31,35,1,5,35,39,2,6,39,43,2,6,43,47,1,5,47,51,2,9,51,55,1,5,55,59,1,10,59,63,1,63,6,67,1,9,67,71,1,71,6,75,1,75,13,79,2,79,13,83,2,9,83,87,1,87,5,91,1,9,91,95,2,10,95,99,1,5,99,103,1,103,9,107,1,13,107,111,2,111,10,115,1,115,5,119,2,13,119,123,1,9,123,127,1,5,127,131,2,131,6,135,1,135,5,139,1,139,6,143,1,143,6,147,1,2,147,151,1,151,5,0,99,2,14,0,0

69
src/day2.rs

@ -0,0 +1,69 @@
use std::io::BufRead;
pub fn part1<F: BufRead> (mut input: F) {
let mut buf = String::new();
let _num_bytes = input.read_line(&mut buf).expect("Unable to first read line of input file");
let mut intcode: Vec<_> = buf.trim().split(",").filter_map(|n| n.parse::<usize>().ok()).collect();
intcode[1] = 12;
intcode[2] = 2;
let output = run_intcode(intcode, 0);
println!("{}", output[0]);
}
fn compute_op(mut src: Vec<usize>, index: usize) -> Vec<usize> {
let lhs = src[src[index + 1]];
let rhs = src[src[index + 2]];
let res = match src[index] {
1 => lhs + rhs,
2 => lhs * rhs,
code => panic!("Unexpected operation {}, should be either 1 or 2", code)
};
let res_index = src[index + 3];
src[res_index] = res;
src
}
fn run_intcode(src: Vec<usize>, index: usize) -> Vec<usize> {
match src[index] {
1 | 2 => run_intcode(compute_op(src, index), index + 4),
99 => src,
code => panic!("Unexpected code {}", code),
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_run_intcode() {
let input1 = vec![1, 0, 0, 0, 99];
let input2 = vec![2, 3, 0, 3, 99];
let input3 = vec![2, 4, 4, 5, 99, 0];
let input4 = vec![1, 1, 1, 4, 99, 5, 6, 0, 99];
let input5 = vec![1,9,10,3,2,3,11,0,99,30,40,50];
let expected1 = vec![2, 0, 0, 0, 99];
let expected2 = vec![2, 3, 0, 6, 99];
let expected3 = vec![2, 4, 4, 5, 99, 9801];
let expected4 = vec![30, 1, 1, 4, 2, 5, 6, 0, 99];
let expected5 = vec![3500,9,10,70, 2,3,11,0, 99, 30,40,50];
let mut output;
output = run_intcode(input1, 0);
assert_eq!(output, expected1);
output = run_intcode(input2, 0);
assert_eq!(output, expected2);
output = run_intcode(input3, 0);
assert_eq!(output, expected3);
output = run_intcode(input4, 0);
assert_eq!(output, expected4);
output = run_intcode(input5, 0);
assert_eq!(output, expected5);
}
}

4
src/main.rs

@ -5,6 +5,7 @@ use std::fs::File;
use std::io::BufReader;
mod day1;
mod day2;
fn main() {
let matches = App::new("Advent of Code 2019")
@ -34,7 +35,8 @@ fn main() {
let reader = BufReader::new(input_file);
let challenges = [
day1::part1, day1::part2
day1::part1, day1::part2,
day2::part1,
];
if let Some(f) = challenges.get(challenge) {

Loading…
Cancel
Save