aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar alecdwm 2019-12-10 23:22:35 +1000
committerGravatar alecdwm 2019-12-10 23:22:35 +1000
commitfff0ba67874010a8ba6ec64fcfc9a39893ba1603 (patch)
treed2ffb2f536df3ede528609bd40fd1986ab37a431
parent3777648c6eeb1141ccab475f63193337073b845e (diff)
added 2019 day9 part1 solution
-rw-r--r--src/lib.rs1
-rw-r--r--src/main.rs1
-rw-r--r--src/year_2019/day9.rs134
-rw-r--r--src/year_2019/intcode_computer.rs80
4 files changed, 192 insertions, 24 deletions
diff --git a/src/lib.rs b/src/lib.rs
index 7148e76..ca43c5c 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -37,4 +37,5 @@ pub mod year_2019 {
pub mod day6;
pub mod day7;
pub mod day8;
+ pub mod day9;
}
diff --git a/src/main.rs b/src/main.rs
index 6f91e3f..259976b 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -35,6 +35,7 @@ fn main() {
puzzle_solutions.insert("2019::day7::part2", advent_of_code::year_2019::day7::part2);
puzzle_solutions.insert("2019::day8::part1", advent_of_code::year_2019::day8::part1);
puzzle_solutions.insert("2019::day8::part2", advent_of_code::year_2019::day8::part2);
+ puzzle_solutions.insert("2019::day9::part1", advent_of_code::year_2019::day9::part1);
let command = match env::args().nth(1) {
Some(command) => command,
diff --git a/src/year_2019/day9.rs b/src/year_2019/day9.rs
new file mode 100644
index 0000000..1833a8c
--- /dev/null
+++ b/src/year_2019/day9.rs
@@ -0,0 +1,134 @@
+//! --- Day 9: Sensor Boost ---
+
+use super::IntcodeComputer;
+
+/// You've just said goodbye to the rebooted rover and left Mars when you receive a faint distress signal coming from the asteroid belt. It must be the Ceres monitoring station!
+///
+/// In order to lock on to the signal, you'll need to boost your sensors. The Elves send up the latest BOOST program - Basic Operation Of System Test.
+///
+/// While BOOST (your puzzle input) is capable of boosting your sensors, for tenuous safety reasons, it refuses to do so until the computer it runs on passes some checks to demonstrate it is a complete Intcode computer.
+///
+/// Your existing Intcode computer is missing one key feature: it needs support for parameters in relative mode.
+///
+/// Parameters in mode 2, relative mode, behave very similarly to parameters in position mode: the parameter is interpreted as a position. Like position mode, parameters in relative mode can be read from or written to.
+///
+/// The important difference is that relative mode parameters don't count from address 0. Instead, they count from a value called the relative base. The relative base starts at 0.
+///
+/// The address a relative mode parameter refers to is itself plus the current relative base. When the relative base is 0, relative mode parameters and position mode parameters with the same value refer to the same address.
+///
+/// For example, given a relative base of 50, a relative mode parameter of -7 refers to memory address 50 + -7 = 43.
+///
+/// The relative base is modified with the relative base offset instruction:
+///
+/// Opcode 9 adjusts the relative base by the value of its only parameter. The relative base increases (or decreases, if the value is negative) by the value of the parameter.
+///
+/// For example, if the relative base is 2000, then after the instruction 109,19, the relative base would be 2019. If the next instruction were 204,-34, then the value at address 1985 would be output.
+///
+/// Your Intcode computer will also need a few other capabilities:
+///
+/// The computer's available memory should be much larger than the initial program. Memory beyond the initial program starts with the value 0 and can be read or written like any other memory. (It is invalid to try to access memory at a negative address, though.)
+/// The computer should have support for large numbers. Some instructions near the beginning of the BOOST program will verify this capability.
+///
+/// Here are some example programs that use these features:
+///
+/// 109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99 takes no input and produces a copy of itself as output.
+/// 1102,34915192,34915192,7,4,7,99,0 should output a 16-digit number.
+/// 104,1125899906842624,99 should output the large number in the middle.
+///
+/// The BOOST program will ask for a single input; run it in test mode by providing it the value 1. It will perform a series of checks on each opcode, output any opcodes (and the associated parameter modes) that seem to be functioning incorrectly, and finally output a BOOST keycode.
+///
+/// Once your Intcode computer is fully functional, the BOOST program should report no malfunctioning opcodes when run in test mode; it should only output a single value, the BOOST keycode. What BOOST keycode does it produce?
+pub fn part1() {
+ let input = crate::common::read_stdin_to_string();
+ let mut computer = IntcodeComputer::from(input.as_str());
+
+ let input_tx = computer.create_input();
+ let output_rx = computer.create_output();
+
+ const TEST_MODE_ID: i64 = 1;
+ input_tx.send(TEST_MODE_ID).unwrap();
+
+ computer.run();
+
+ let result: Vec<i64> = output_rx.try_iter().collect();
+
+ println!(
+ "The program output: {:?}",
+ result
+ .iter()
+ .map(|integer| integer.to_string())
+ .collect::<Vec<_>>()
+ .join(",")
+ );
+ println!(
+ "The BOOST keycode produced: {}",
+ result.last().expect("No output")
+ );
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_intcode_computer_echo() {
+ let example = (
+ "109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99",
+ 109,
+ 1,
+ 204,
+ -1,
+ 1001,
+ 100,
+ 1,
+ 100,
+ 1008,
+ 100,
+ 16,
+ 101,
+ 1006,
+ 101,
+ 0,
+ 99,
+ );
+
+ let mut computer = IntcodeComputer::from(example.0);
+ let output_rx = computer.create_output();
+
+ computer.run();
+
+ assert_eq!(output_rx.recv().unwrap(), example.1);
+ assert_eq!(output_rx.recv().unwrap(), example.2);
+ assert_eq!(output_rx.recv().unwrap(), example.3);
+ assert_eq!(output_rx.recv().unwrap(), example.4);
+ assert_eq!(output_rx.recv().unwrap(), example.5);
+ assert_eq!(output_rx.recv().unwrap(), example.6);
+ assert_eq!(output_rx.recv().unwrap(), example.7);
+ assert_eq!(output_rx.recv().unwrap(), example.8);
+ assert_eq!(output_rx.recv().unwrap(), example.9);
+ assert_eq!(output_rx.recv().unwrap(), example.10);
+ assert_eq!(output_rx.recv().unwrap(), example.11);
+ assert_eq!(output_rx.recv().unwrap(), example.12);
+ assert_eq!(output_rx.recv().unwrap(), example.13);
+ assert_eq!(output_rx.recv().unwrap(), example.14);
+ assert_eq!(output_rx.recv().unwrap(), example.15);
+ assert_eq!(output_rx.recv().unwrap(), example.16);
+ }
+
+ #[test]
+ fn test_part1_examples() {
+ let examples = [
+ ("1102,34915192,34915192,7,4,7,99,0", 1219070632396864),
+ ("104,1125899906842624,99", 1125899906842624),
+ ];
+
+ for example in &examples {
+ let mut computer = IntcodeComputer::from(example.0);
+ let output_rx = computer.create_output();
+
+ computer.run();
+
+ assert_eq!(output_rx.recv().unwrap(), example.1);
+ }
+ }
+}
diff --git a/src/year_2019/intcode_computer.rs b/src/year_2019/intcode_computer.rs
index a73e38b..e72a72e 100644
--- a/src/year_2019/intcode_computer.rs
+++ b/src/year_2019/intcode_computer.rs
@@ -6,6 +6,7 @@ use std::thread;
pub struct IntcodeComputer {
pub memory: IntcodeProgram,
instruction_pointer: usize,
+ relative_base: i64,
input: Option<Receiver<i64>>,
output: Option<Sender<i64>>,
}
@@ -14,6 +15,7 @@ impl IntcodeComputer {
pub fn load(&mut self, program: &IntcodeProgram) {
self.memory = program.clone();
self.instruction_pointer = 0;
+ self.relative_base = 0;
}
pub fn run_new_in_thread(program: IntcodeProgram) -> (Sender<i64>, Receiver<i64>) {
@@ -51,20 +53,20 @@ impl IntcodeComputer {
match next_instruction {
IntcodeInstruction::Add(one, two, output) => {
- let one = one.get_value(&self.memory);
- let two = two.get_value(&self.memory);
+ let one = one.get_value(&self);
+ let two = two.get_value(&self);
let output_address = output
- .get_address()
+ .get_address(&self)
.expect("Add 'output' parameter must be an address");
self.memory.replace(output_address, one + two)
}
IntcodeInstruction::Multiply(one, two, output) => {
- let one = one.get_value(&self.memory);
- let two = two.get_value(&self.memory);
+ let one = one.get_value(&self);
+ let two = two.get_value(&self);
let output_address = output
- .get_address()
+ .get_address(&self)
.expect("Multiply 'output' parameter must be an address");
self.memory.replace(output_address, one * two)
@@ -79,14 +81,14 @@ impl IntcodeComputer {
.expect("Failed to receive from input");
let to_address = to
- .get_address()
+ .get_address(&self)
.expect("Input 'to' parameter must be an address");
self.memory.replace(to_address, input_value);
}
IntcodeInstruction::Output(from) => {
- let output_value = from.get_value(&self.memory);
+ let output_value = from.get_value(&self);
self.output
.as_ref()
@@ -96,45 +98,49 @@ impl IntcodeComputer {
}
IntcodeInstruction::JumpIfTrue(test, jump_to) => {
- if test.get_value(&self.memory) != 0 {
- self.instruction_pointer =
- jump_to.get_value(&self.memory).try_into().unwrap();
+ if test.get_value(&self) != 0 {
+ self.instruction_pointer = jump_to.get_value(&self).try_into().unwrap();
}
}
IntcodeInstruction::JumpIfFalse(test, jump_to) => {
- if test.get_value(&self.memory) == 0 {
- self.instruction_pointer =
- jump_to.get_value(&self.memory).try_into().unwrap();
+ if test.get_value(&self) == 0 {
+ self.instruction_pointer = jump_to.get_value(&self).try_into().unwrap();
}
}
IntcodeInstruction::LessThan(one, two, output) => {
- let one = one.get_value(&self.memory);
- let two = two.get_value(&self.memory);
+ let one = one.get_value(&self);
+ let two = two.get_value(&self);
let output_value = if one < two { 1 } else { 0 };
let output_address = output
- .get_address()
+ .get_address(&self)
.expect("LessThan 'output' parameter must be an address");
self.memory.replace(output_address, output_value)
}
IntcodeInstruction::Equals(one, two, output) => {
- let one = one.get_value(&self.memory);
- let two = two.get_value(&self.memory);
+ let one = one.get_value(&self);
+ let two = two.get_value(&self);
let output_value = if one == two { 1 } else { 0 };
let output_address = output
- .get_address()
+ .get_address(&self)
.expect("LessThan 'output' parameter must be an address");
self.memory.replace(output_address, output_value)
}
+ IntcodeInstruction::RelativeBaseOffset(offset) => {
+ let offset = offset.get_value(&self);
+
+ self.relative_base = self.relative_base + offset;
+ }
+
IntcodeInstruction::Halt => break,
}
@@ -150,6 +156,7 @@ impl From<&IntcodeProgram> for IntcodeComputer {
Self {
memory: program.clone(),
instruction_pointer: 0,
+ relative_base: 0,
input: None,
output: None,
}
@@ -161,6 +168,7 @@ impl From<&str> for IntcodeComputer {
Self {
memory: IntcodeProgram::from(string),
instruction_pointer: 0,
+ relative_base: 0,
input: None,
output: None,
}
@@ -195,6 +203,9 @@ enum IntcodeInstruction {
/// Otherwise, writes 0 to the third parameter.
Equals(IntcodeParameter, IntcodeParameter, IntcodeParameter),
+ /// Adjusts the relative base by the value of its only parameter.
+ RelativeBaseOffset(IntcodeParameter),
+
/// Halts the IntcodeComputer
Halt,
}
@@ -210,6 +221,7 @@ impl IntcodeInstruction {
Self::JumpIfFalse(..) => 3,
Self::LessThan(..) => 4,
Self::Equals(..) => 4,
+ Self::RelativeBaseOffset(..) => 2,
Self::Halt => 1,
}
}
@@ -256,6 +268,9 @@ impl From<&IntcodeComputer> for IntcodeInstruction {
parser.parse_next(state.memory.get(state.instruction_pointer + 2)),
parser.parse_writeonly(state.memory.get(state.instruction_pointer + 3)),
),
+ Opcode(9) => Self::RelativeBaseOffset(
+ parser.parse_next(state.memory.get(state.instruction_pointer + 1)),
+ ),
Opcode(99) => Self::Halt,
Opcode(other) => panic!("Invalid Opcode encountered: {}", other),
}
@@ -277,20 +292,27 @@ enum IntcodeParameter {
/// ImmediateMode
Value(i64),
+
+ /// RelativeMode
+ Relative(i64),
}
impl IntcodeParameter {
- fn get_address(&self) -> Option<usize> {
+ fn get_address(&self, computer: &IntcodeComputer) -> Option<usize> {
match self {
Self::Position(address) => Some(*address),
Self::Value(_) => None,
+ Self::Relative(address) => Some((computer.relative_base + address).try_into().unwrap()),
}
}
- fn get_value(&self, memory: &IntcodeProgram) -> i64 {
+ fn get_value(&self, computer: &IntcodeComputer) -> i64 {
match self {
- Self::Position(address) => memory.get(*address),
+ Self::Position(address) => computer.memory.get(*address),
Self::Value(value) => *value,
+ Self::Relative(address) => computer
+ .memory
+ .get((computer.relative_base + address).try_into().unwrap()),
}
}
}
@@ -318,6 +340,7 @@ impl ParameterParser {
IntcodeParameter::Position(parameter.try_into().unwrap())
}
ParameterMode::ImmediateMode => IntcodeParameter::Value(parameter),
+ ParameterMode::RelativeMode => IntcodeParameter::Relative(parameter),
};
self.parameters_read += 1;
@@ -326,7 +349,14 @@ impl ParameterParser {
}
fn parse_writeonly(&mut self, parameter: i64) -> IntcodeParameter {
- let parameter = IntcodeParameter::Position(parameter.try_into().unwrap());
+ let mode = ParameterMode::from(&*self);
+ let parameter = match mode {
+ ParameterMode::PositionMode => {
+ IntcodeParameter::Position(parameter.try_into().unwrap())
+ }
+ ParameterMode::ImmediateMode => panic!("ImmediateMode invalid for writeonly parameter"),
+ ParameterMode::RelativeMode => IntcodeParameter::Relative(parameter),
+ };
self.parameters_read += 1;
@@ -338,6 +368,7 @@ impl ParameterParser {
enum ParameterMode {
PositionMode,
ImmediateMode,
+ RelativeMode,
}
impl From<&ParameterParser> for ParameterMode {
@@ -345,6 +376,7 @@ impl From<&ParameterParser> for ParameterMode {
match get_digit(state.instruction_header, 2 + state.parameters_read) {
0 => Self::PositionMode,
1 => Self::ImmediateMode,
+ 2 => Self::RelativeMode,
other => panic!("Invalid ParameterMode: {}", other),
}
}