From 79645abe5a28a0175c2e2174780c4e2c60f77c07 Mon Sep 17 00:00:00 2001 From: Tyler Hallada Date: Sat, 4 Jan 2020 16:58:56 -0500 Subject: [PATCH] Completed day 11 --- day11/Cargo.lock | 137 +++++++++++++ day11/Cargo.toml | 10 + day11/input/input.txt | 1 + day11/src/intcode.rs | 461 ++++++++++++++++++++++++++++++++++++++++++ day11/src/main.rs | 189 +++++++++++++++++ 5 files changed, 798 insertions(+) create mode 100644 day11/Cargo.lock create mode 100644 day11/Cargo.toml create mode 100644 day11/input/input.txt create mode 100644 day11/src/intcode.rs create mode 100644 day11/src/main.rs diff --git a/day11/Cargo.lock b/day11/Cargo.lock new file mode 100644 index 0000000..15649e1 --- /dev/null +++ b/day11/Cargo.lock @@ -0,0 +1,137 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "day11" +version = "0.1.0" +dependencies = [ + "num_enum 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "derivative" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 0.15.44 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "num_enum" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "derivative 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "num_enum_derive 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "num_enum_derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro-crate 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro2 1.0.7 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 1.0.13 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "proc-macro-crate" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "toml 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "proc-macro2" +version = "0.4.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "proc-macro2" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "quote" +version = "0.6.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "quote" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 1.0.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "serde" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "syn" +version = "0.15.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "syn" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 1.0.7 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "toml" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "unicode-xid" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "unicode-xid" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum derivative 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "942ca430eef7a3806595a6737bc388bf51adb888d3fc0dd1b50f1c170167ee3a" +"checksum num_enum 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "be601e38e20a6f3d01049d85801cb9b7a34a8da7a0da70df507bbde7735058c8" +"checksum num_enum_derive 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "b59f30f6a043f2606adbd0addbf1eef6f2e28e8c4968918b63b7ff97ac0db2a7" +"checksum proc-macro-crate 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "e10d4b51f154c8a7fb96fd6dad097cb74b863943ec010ac94b9fd1be8861fe1e" +"checksum proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)" = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759" +"checksum proc-macro2 1.0.7 (registry+https://github.com/rust-lang/crates.io-index)" = "0319972dcae462681daf4da1adeeaa066e3ebd29c69be96c6abb1259d2ee2bcc" +"checksum quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)" = "6ce23b6b870e8f94f81fb0a363d65d86675884b34a09043c81e5562f11c1f8e1" +"checksum quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "053a8c8bcc71fcce321828dc897a98ab9760bef03a4fc36693c231e5b3216cfe" +"checksum serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)" = "414115f25f818d7dfccec8ee535d76949ae78584fc4f79a6f45a904bf8ab4449" +"checksum syn 0.15.44 (registry+https://github.com/rust-lang/crates.io-index)" = "9ca4b3b69a77cbe1ffc9e198781b7acb0c7365a883670e8f1c1bc66fba79a5c5" +"checksum syn 1.0.13 (registry+https://github.com/rust-lang/crates.io-index)" = "1e4ff033220a41d1a57d8125eab57bf5263783dfdcc18688b1dacc6ce9651ef8" +"checksum toml 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)" = "01d1404644c8b12b16bfcffa4322403a91a451584daaaa7c28d3152e6cbc98cf" +"checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" +"checksum unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c" diff --git a/day11/Cargo.toml b/day11/Cargo.toml new file mode 100644 index 0000000..6ea2497 --- /dev/null +++ b/day11/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "day11" +version = "0.1.0" +authors = ["Tyler Hallada "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +num_enum = "0.4.2" diff --git a/day11/input/input.txt b/day11/input/input.txt new file mode 100644 index 0000000..2a4e083 --- /dev/null +++ b/day11/input/input.txt @@ -0,0 +1 @@ +3,8,1005,8,338,1106,0,11,0,0,0,104,1,104,0,3,8,1002,8,-1,10,1001,10,1,10,4,10,108,1,8,10,4,10,102,1,8,28,1,108,6,10,1,3,7,10,3,8,1002,8,-1,10,1001,10,1,10,4,10,108,1,8,10,4,10,1001,8,0,58,2,5,19,10,1,1008,7,10,2,105,6,10,1,1007,7,10,3,8,1002,8,-1,10,1001,10,1,10,4,10,1008,8,0,10,4,10,101,0,8,97,1006,0,76,1,106,14,10,2,9,9,10,1006,0,74,3,8,102,-1,8,10,101,1,10,10,4,10,108,1,8,10,4,10,1002,8,1,132,1006,0,0,2,1104,15,10,3,8,1002,8,-1,10,1001,10,1,10,4,10,1008,8,0,10,4,10,1001,8,0,162,1,1005,13,10,3,8,1002,8,-1,10,101,1,10,10,4,10,108,1,8,10,4,10,101,0,8,187,1,1,15,10,2,3,9,10,1006,0,54,3,8,102,-1,8,10,101,1,10,10,4,10,108,0,8,10,4,10,102,1,8,220,1,104,5,10,3,8,102,-1,8,10,101,1,10,10,4,10,1008,8,0,10,4,10,102,1,8,247,1,5,1,10,1,1109,2,10,3,8,1002,8,-1,10,101,1,10,10,4,10,1008,8,0,10,4,10,1001,8,0,277,1006,0,18,3,8,1002,8,-1,10,101,1,10,10,4,10,108,1,8,10,4,10,101,0,8,301,2,105,14,10,1,5,1,10,2,1009,6,10,1,3,0,10,101,1,9,9,1007,9,1054,10,1005,10,15,99,109,660,104,0,104,1,21101,0,47677546524,1,21101,0,355,0,1105,1,459,21102,936995299356,1,1,21101,0,366,0,1106,0,459,3,10,104,0,104,1,3,10,104,0,104,0,3,10,104,0,104,1,3,10,104,0,104,1,3,10,104,0,104,0,3,10,104,0,104,1,21101,0,206312807515,1,21102,1,413,0,1105,1,459,21101,206253871296,0,1,21102,424,1,0,1106,0,459,3,10,104,0,104,0,3,10,104,0,104,0,21102,1,709580554600,1,21102,1,447,0,1105,1,459,21101,0,868401967464,1,21101,458,0,0,1106,0,459,99,109,2,22102,1,-1,1,21102,1,40,2,21101,0,490,3,21102,480,1,0,1106,0,523,109,-2,2105,1,0,0,1,0,0,1,109,2,3,10,204,-1,1001,485,486,501,4,0,1001,485,1,485,108,4,485,10,1006,10,517,1101,0,0,485,109,-2,2105,1,0,0,109,4,2101,0,-1,522,1207,-3,0,10,1006,10,540,21102,0,1,-3,21201,-3,0,1,21202,-2,1,2,21101,0,1,3,21101,0,559,0,1105,1,564,109,-4,2106,0,0,109,5,1207,-3,1,10,1006,10,587,2207,-4,-2,10,1006,10,587,21202,-4,1,-4,1105,1,655,21201,-4,0,1,21201,-3,-1,2,21202,-2,2,3,21102,606,1,0,1105,1,564,22102,1,1,-4,21102,1,1,-1,2207,-4,-2,10,1006,10,625,21102,1,0,-1,22202,-2,-1,-2,2107,0,-3,10,1006,10,647,22101,0,-1,1,21101,0,647,0,106,0,522,21202,-2,-1,-2,22201,-4,-2,-4,109,-5,2106,0,0 diff --git a/day11/src/intcode.rs b/day11/src/intcode.rs new file mode 100644 index 0000000..20fbfa8 --- /dev/null +++ b/day11/src/intcode.rs @@ -0,0 +1,461 @@ +use std::collections::HashMap; +use std::convert::TryFrom; +use std::error::Error; +use std::fs::File; +use std::io::prelude::*; +use std::result; +use std::str::FromStr; + +use num_enum::TryFromPrimitive; + +type Result = result::Result>; + +#[derive(Debug, Clone, PartialEq)] +pub struct Intcode { + pub integers: HashMap, + pub pointer: usize, + pub halted: bool, + pub relative_base: i64, +} + +#[derive(Debug, PartialEq)] +pub struct Instruction { + opcode: Opcode, + parameter_modes: Vec, +} + +impl TryFrom for Instruction { + type Error = Box; + + fn try_from(integer: i64) -> Result { + let opcode: Opcode = Opcode::try_from((integer % 100) as u8)?; + let modes_integer = integer / 100; + let mut parameter_modes = vec![]; + for parameter_index in 0..opcode.parameter_count() { + parameter_modes.push(ParameterMode::try_from( + (modes_integer % (10_i64.pow(parameter_index + 1)) / 10_i64.pow(parameter_index)) + as u8, + )?) + } + Ok(Instruction { + opcode, + parameter_modes, + }) + } +} + +#[derive(Debug, PartialEq, TryFromPrimitive)] +#[repr(u8)] +pub enum Opcode { + Add = 1, + Mult = 2, + Input = 3, + Output = 4, + JumpIfTrue = 5, + JumpIfFalse = 6, + LessThan = 7, + Equals = 8, + RelativeBaseOffset = 9, + Halt = 99, +} + +impl Opcode { + pub fn parameter_count(&self) -> u32 { + match self { + Opcode::Add => 3, + Opcode::Mult => 3, + Opcode::Input => 1, + Opcode::Output => 1, + Opcode::JumpIfTrue => 2, + Opcode::JumpIfFalse => 2, + Opcode::LessThan => 3, + Opcode::Equals => 3, + Opcode::RelativeBaseOffset => 1, + Opcode::Halt => 0, + } + } + + pub fn target_parameter_index(&self) -> Option { + match self { + Opcode::Add => Some(2), + Opcode::Mult => Some(2), + Opcode::Input => Some(0), + Opcode::Output => None, + Opcode::JumpIfTrue => None, + Opcode::JumpIfFalse => None, + Opcode::LessThan => Some(2), + Opcode::Equals => Some(2), + Opcode::RelativeBaseOffset => None, + Opcode::Halt => None, + } + } +} + +#[derive(Debug, PartialEq, TryFromPrimitive)] +#[repr(u8)] +pub enum ParameterMode { + Position = 0, + Immediate = 1, + Relative = 2, +} + +impl FromStr for Intcode { + type Err = Box; + + fn from_str(s: &str) -> Result { + let intcode_string = s.trim().to_string(); + let mut integers = HashMap::new(); + for (index, code) in intcode_string.split(',').enumerate() { + integers.insert(index, code.parse().unwrap()); + } + + Ok(Intcode::new(integers)) + } +} + +impl Intcode { + fn new(integers: HashMap) -> Intcode { + Intcode { + integers, + pointer: 0, + halted: false, + relative_base: 0, + } + } + + fn load_parameters(&mut self, pointer: usize, instruction: &Instruction) -> Vec { + (0..instruction.opcode.parameter_count() as usize) + .map(|parameter_index| { + let mut integer = *self + .integers + .entry(pointer + parameter_index + 1) + .or_insert(0); + match instruction.parameter_modes[parameter_index] { + ParameterMode::Position => match instruction.opcode.target_parameter_index() { + Some(target_parameter_index) + if target_parameter_index == parameter_index => {} + _ => { + integer = *self.integers.entry(integer as usize).or_insert(0); + } + }, + ParameterMode::Relative => match instruction.opcode.target_parameter_index() { + Some(target_parameter_index) + if target_parameter_index == parameter_index => + { + integer += self.relative_base; + } + _ => { + integer = *self + .integers + .entry((self.relative_base + integer) as usize) + .or_insert(0); + } + }, + _ => {} + } + integer + }) + .collect() + } + + pub fn execute(&mut self, inputs: &[i64]) -> Result> { + let mut input_index = 0; + let mut output = vec![]; + + loop { + let instruction = + Instruction::try_from(*self.integers.entry(self.pointer).or_insert(0))?; + let parameters = self.load_parameters(self.pointer, &instruction); + let mut jump_pointer: Option = None; + + match instruction.opcode { + Opcode::Add => { + self.integers + .insert(parameters[2] as usize, parameters[0] + parameters[1]); + } + Opcode::Mult => { + self.integers + .insert(parameters[2] as usize, parameters[0] * parameters[1]); + } + Opcode::Input => { + if input_index >= inputs.len() { + break; // pause execution to wait for more input + } + self.integers + .insert(parameters[0] as usize, inputs[input_index]); + input_index += 1; + } + Opcode::Output => { + output.push(parameters[0]); + } + Opcode::JumpIfTrue => { + if parameters[0] != 0 { + jump_pointer = Some(parameters[1] as usize); + } + } + Opcode::JumpIfFalse => { + if parameters[0] == 0 { + jump_pointer = Some(parameters[1] as usize); + } + } + Opcode::LessThan => { + if parameters[0] < parameters[1] { + self.integers.insert(parameters[2] as usize, 1); + } else { + self.integers.insert(parameters[2] as usize, 0); + } + } + Opcode::Equals => { + if parameters[0] == parameters[1] { + self.integers.insert(parameters[2] as usize, 1); + } else { + self.integers.insert(parameters[2] as usize, 0); + } + } + Opcode::RelativeBaseOffset => { + self.relative_base += parameters[0]; + } + Opcode::Halt => { + self.halted = true; + break; + } + } + + match jump_pointer { + Some(jump_pointer) => self.pointer = jump_pointer, + None => self.pointer += 1 + instruction.opcode.parameter_count() as usize, + } + } + + Ok(output) + } +} + +pub fn read_intcode(filename: &str) -> Result { + let mut file = File::open(filename)?; + let mut intcode_string = String::new(); + file.read_to_string(&mut intcode_string)?; + + Ok(intcode_string.parse()?) +} + +#[cfg(test)] +mod tests { + use super::*; + + const TEST_INPUT: &str = "input/test1.txt"; + + #[test] + fn reads_intcode() { + assert_eq!( + read_intcode(TEST_INPUT).unwrap(), + Intcode::new( + vec![3, 15, 3, 16, 1002, 16, 10, 16, 1, 16, 15, 15, 4, 15, 99, 0, 0] + .into_iter() + .enumerate() + .collect() + ), + ); + } + + #[test] + fn converts_integer_to_instruction() { + assert_eq!( + Instruction::try_from(1002).unwrap(), + Instruction { + opcode: Opcode::Mult, + parameter_modes: vec![ + ParameterMode::Position, + ParameterMode::Immediate, + ParameterMode::Position + ], + } + ); + + assert_eq!( + Instruction::try_from(101).unwrap(), + Instruction { + opcode: Opcode::Add, + parameter_modes: vec![ + ParameterMode::Immediate, + ParameterMode::Position, + ParameterMode::Position + ], + } + ); + } + + #[test] + fn executes_intcodes() { + let mut intcode = Intcode::new(vec![1, 0, 0, 0, 99].into_iter().enumerate().collect()); + intcode.execute(&[0]).unwrap(); + assert_eq!( + intcode.integers, + vec![2, 0, 0, 0, 99].into_iter().enumerate().collect() + ); + + let mut intcode = Intcode::new(vec![2, 3, 0, 3, 99].into_iter().enumerate().collect()); + intcode.execute(&[0]).unwrap(); + assert_eq!( + intcode.integers, + vec![2, 3, 0, 6, 99].into_iter().enumerate().collect() + ); + + let mut intcode = Intcode::new(vec![2, 4, 4, 5, 99, 0].into_iter().enumerate().collect()); + intcode.execute(&[0]).unwrap(); + assert_eq!( + intcode.integers, + vec![2, 4, 4, 5, 99, 9801].into_iter().enumerate().collect() + ); + + let mut intcode = Intcode::new( + vec![1, 1, 1, 4, 99, 5, 6, 0, 99] + .into_iter() + .enumerate() + .collect(), + ); + intcode.execute(&[0]).unwrap(); + assert_eq!( + intcode.integers, + vec![30, 1, 1, 4, 2, 5, 6, 0, 99] + .into_iter() + .enumerate() + .collect() + ); + + let mut intcode = Intcode::new( + vec![1, 9, 10, 3, 2, 3, 11, 0, 99, 30, 40, 50] + .into_iter() + .enumerate() + .collect(), + ); + intcode.execute(&[0]).unwrap(); + assert_eq!( + intcode.integers, + vec![3500, 9, 10, 70, 2, 3, 11, 0, 99, 30, 40, 50] + .into_iter() + .enumerate() + .collect() + ); + } + + #[test] + fn less_and_equal_outputs() { + let intcode = Intcode::new( + vec![3, 9, 8, 9, 10, 9, 4, 9, 99, -1, 8] + .into_iter() + .enumerate() + .collect(), + ); + assert_eq!(intcode.clone().execute(&[8]).unwrap(), vec![1]); + assert_eq!(intcode.clone().execute(&[0]).unwrap(), vec![0]); + + let intcode = Intcode::new( + vec![3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8] + .into_iter() + .enumerate() + .collect(), + ); + assert_eq!(intcode.clone().execute(&[0]).unwrap(), vec![1]); + assert_eq!(intcode.clone().execute(&[9]).unwrap(), vec![0]); + + let intcode = Intcode::new( + vec![3, 3, 1108, -1, 8, 3, 4, 3, 99] + .into_iter() + .enumerate() + .collect(), + ); + assert_eq!(intcode.clone().execute(&[8]).unwrap(), vec![1]); + assert_eq!(intcode.clone().execute(&[0]).unwrap(), vec![0]); + + let intcode = Intcode::new( + vec![3, 3, 1107, -1, 8, 3, 4, 3, 99] + .into_iter() + .enumerate() + .collect(), + ); + assert_eq!(intcode.clone().execute(&[0]).unwrap(), vec![1]); + assert_eq!(intcode.clone().execute(&[9]).unwrap(), vec![0]); + } + + #[test] + fn jump_outputs() { + let intcode = Intcode::new( + vec![3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, -1, 0, 1, 9] + .into_iter() + .enumerate() + .collect(), + ); + assert_eq!(intcode.clone().execute(&[0]).unwrap(), vec![0]); + assert_eq!(intcode.clone().execute(&[1]).unwrap(), vec![1]); + + let intcode = Intcode::new( + vec![3, 3, 1105, -1, 9, 1101, 0, 0, 12, 4, 12, 99, 1] + .into_iter() + .enumerate() + .collect(), + ); + assert_eq!(intcode.clone().execute(&[0]).unwrap(), vec![0]); + assert_eq!(intcode.clone().execute(&[1]).unwrap(), vec![1]); + } + + #[test] + fn larger_part2_intcode() { + let intcode = Intcode::new( + vec![ + 3, 21, 1008, 21, 8, 20, 1005, 20, 22, 107, 8, 21, 20, 1006, 20, 31, 1106, 0, 36, + 98, 0, 0, 1002, 21, 125, 20, 4, 20, 1105, 1, 46, 104, 999, 1105, 1, 46, 1101, 1000, + 1, 20, 4, 20, 1105, 1, 46, 98, 99, + ] + .into_iter() + .enumerate() + .collect(), + ); + assert_eq!(intcode.clone().execute(&[0]).unwrap(), vec![999]); + assert_eq!(intcode.clone().execute(&[8]).unwrap(), vec![1000]); + assert_eq!(intcode.clone().execute(&[9]).unwrap(), vec![1001]); + } + + #[test] + fn multiple_input_intcode() { + let intcode = Intcode::new( + vec![ + 3, 15, 3, 16, 1002, 16, 10, 16, 1, 16, 15, 15, 4, 15, 99, 0, 0, + ] + .into_iter() + .enumerate() + .collect(), + ); + assert_eq!(intcode.clone().execute(&[1, 1]).unwrap(), vec![11]); + } + + #[test] + fn relative_base_offset_quine() { + let code = vec![ + 109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99, + ]; + let intcode = Intcode::new(code.clone().into_iter().enumerate().collect()); + assert_eq!(intcode.clone().execute(&[]).unwrap(), code); + } + + #[test] + fn sixteen_digit_output() { + let code = vec![1102, 34915192, 34915192, 7, 4, 7, 99, 0]; + let intcode = Intcode::new(code.into_iter().enumerate().collect()); + assert_eq!(intcode.clone().execute(&[]).unwrap(), [1219070632396864]); + } + + #[test] + fn large_output() { + let code = vec![104, 1125899906842624, 99]; + let intcode = Intcode::new(code.into_iter().enumerate().collect()); + assert_eq!(intcode.clone().execute(&[]).unwrap(), [1125899906842624]); + } + + #[test] + fn relative_target_parameters() { + let code = vec![109, 1, 203, 2, 204, 2, 99]; + let intcode = Intcode::new(code.into_iter().enumerate().collect()); + assert_eq!(intcode.clone().execute(&[123]).unwrap(), [123]); + } +} diff --git a/day11/src/main.rs b/day11/src/main.rs new file mode 100644 index 0000000..f332091 --- /dev/null +++ b/day11/src/main.rs @@ -0,0 +1,189 @@ +use std::collections::HashMap; +use std::convert::TryFrom; +use std::error::Error; +use std::fmt; +use std::result; + +use num_enum::TryFromPrimitive; + +mod intcode; + +use intcode::{read_intcode, Intcode}; + +const INPUT: &str = "input/input.txt"; + +type Result = result::Result>; + +#[derive(TryFromPrimitive, Clone, Copy)] +#[repr(u8)] +enum Color { + Black = 0, + White = 1, +} + +#[derive(TryFromPrimitive, Clone, Copy)] +#[repr(u8)] +enum Turn { + Left = 0, + Right = 1, +} + +#[derive(TryFromPrimitive, Clone, Copy)] +#[repr(u8)] +enum Direction { + Left = 0, + Right = 1, + Up = 2, + Down = 3, +} + +impl Direction { + fn turn(&self, turn: Turn) -> Direction { + match turn { + Turn::Left => match self { + Direction::Left => Direction::Down, + Direction::Right => Direction::Up, + Direction::Up => Direction::Left, + Direction::Down => Direction::Right, + }, + Turn::Right => match self { + Direction::Left => Direction::Up, + Direction::Right => Direction::Down, + Direction::Up => Direction::Right, + Direction::Down => Direction::Left, + }, + } + } +} + +#[derive(PartialEq, Eq, Hash, Clone, Copy)] +struct Coordinate { + x: i64, + y: i64, +} + +struct Robot { + intcode: Intcode, + position: Coordinate, + direction: Direction, +} + +impl Robot { + fn new(intcode: Intcode) -> Robot { + Robot { + intcode: intcode.clone(), + position: Coordinate { x: 0, y: 0 }, + direction: Direction::Up, + } + } + + fn turn_and_move(&mut self, turn: Turn) { + self.direction = self.direction.turn(turn); + match self.direction { + Direction::Left => self.position.x -= 1, + Direction::Right => self.position.x += 1, + Direction::Up => self.position.y -= 1, + Direction::Down => self.position.y += 1, + } + } +} + +struct Hull { + panels: HashMap, +} + +impl Hull { + fn new() -> Hull { + Hull { + panels: HashMap::new(), + } + } + + fn paint_registration(&mut self, intcode: Intcode, start_color: Color) -> Result<()> { + let mut robot = Robot::new(intcode); + let mut current_panel = start_color; + while !robot.intcode.halted { + let output = robot + .intcode + .execute(&[current_panel as i64]) + .expect("Failed to execute intcode"); + let color = Color::try_from(output[0] as u8)?; + let turn = Turn::try_from(output[1] as u8)?; + + self.panels.insert(robot.position, color); + robot.turn_and_move(turn); + current_panel = *self.panels.get(&robot.position).unwrap_or(&Color::Black); + } + Ok(()) + } +} + +impl fmt::Display for Hull { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let start_coord = Coordinate { x: 0, y: 0 }; + let up_left_corner = Coordinate { + x: self + .panels + .keys() + .min_by_key(|coord| coord.x) + .unwrap_or(&start_coord) + .x, + y: self + .panels + .keys() + .min_by_key(|coord| coord.y) + .unwrap_or(&start_coord) + .y, + }; + let down_right_corner = Coordinate { + x: self + .panels + .keys() + .max_by_key(|coord| coord.x) + .unwrap_or(&start_coord) + .x, + y: self + .panels + .keys() + .max_by_key(|coord| coord.y) + .unwrap_or(&start_coord) + .y, + }; + for y in up_left_corner.y..=down_right_corner.y { + let mut row_string = String::new(); + for x in up_left_corner.x..=down_right_corner.x { + row_string += match self + .panels + .get(&Coordinate { x, y }) + .unwrap_or(&Color::Black) + { + Color::Black => ".", + Color::White => "#", + }; + } + write!(f, "{}\n", row_string)?; + } + Ok(()) + } +} + +fn solve_part1() -> Result { + let intcode = read_intcode(INPUT)?; + let mut hull = Hull::new(); + hull.paint_registration(intcode, Color::Black)?; + Ok(hull.panels.len()) +} + +fn solve_part2() -> Result { + let intcode = read_intcode(INPUT)?; + let mut hull = Hull::new(); + hull.paint_registration(intcode, Color::White)?; + Ok(format!("\n{}", hull)) +} + +fn main() -> Result<()> { + println!("Part 1: {}", solve_part1()?); + println!("Part 2: {}", solve_part2()?); + + Ok(()) +}