diff options
author | Justin Wernick <justin@worthe-it.co.za> | 2019-12-02 22:22:23 +0200 |
---|---|---|
committer | Justin Wernick <justin@worthe-it.co.za> | 2019-12-02 22:22:23 +0200 |
commit | 3988b89729bda5d43f36c2de65ad88000c6c6b02 (patch) | |
tree | 15185e615f7f5b37ff8aaf4dce0d86ac17650a34 /src/bin | |
parent | 203431863570652f859ba4fe76dda5a5ea8ccac3 (diff) |
Abstract the repeated code
Diffstat (limited to 'src/bin')
-rw-r--r-- | src/bin/day_2.rs | 29 |
1 files changed, 11 insertions, 18 deletions
diff --git a/src/bin/day_2.rs b/src/bin/day_2.rs index 184c06c..f1a1ac7 100644 --- a/src/bin/day_2.rs +++ b/src/bin/day_2.rs @@ -140,15 +140,7 @@ impl Program { } fn add(&self) -> Program { - match ( - self.codes - .get(self.program_counter + 1) - .and_then(|r| self.codes.get(*r as usize)), - self.codes - .get(self.program_counter + 2) - .and_then(|r| self.codes.get(*r as usize)), - self.codes.get(self.program_counter + 3), - ) { + match (self.get_deref(1), self.get_dered(2), self.get(3)) { (Some(in1), Some(in2), Some(out)) => Program { program_counter: self.program_counter + 4, codes: self.codes.update(*out as usize, in1 + in2), @@ -159,15 +151,7 @@ impl Program { } fn multiply(&self) -> Program { - match ( - self.codes - .get(self.program_counter + 1) - .and_then(|r| self.codes.get(*r as usize)), - self.codes - .get(self.program_counter + 2) - .and_then(|r| self.codes.get(*r as usize)), - self.codes.get(self.program_counter + 3), - ) { + match (self.get_deref(1), self.get_dered(2), self.get(3)) { (Some(in1), Some(in2), Some(out)) => Program { program_counter: self.program_counter + 4, codes: self.codes.update(*out as usize, in1 * in2), @@ -191,6 +175,15 @@ impl Program { ..self.clone() } } + + fn get(&self, pointer_offset: usize) -> Option<Intcode> { + self.codes.get(self.program_counter + pointer_offset) + } + + fn get_deref(&self, pointer_offset: usize) -> Option<Intcode> { + self.get(pointer_offset) + .and_then(|r| self.codes.get(*r as usize)) + } } #[derive(Debug, PartialEq)] |