From 38f1b5a037d0b9ef6613a03587b7998bd5360d4d Mon Sep 17 00:00:00 2001 From: "max.nuding" Date: Fri, 2 Dec 2022 07:06:34 +0100 Subject: [PATCH] Day 02 --- src/day02/mod.rs | 82 +++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 75 insertions(+), 7 deletions(-) diff --git a/src/day02/mod.rs b/src/day02/mod.rs index 34e088b..cb39c04 100644 --- a/src/day02/mod.rs +++ b/src/day02/mod.rs @@ -1,17 +1,78 @@ use crate::read; struct Hand { - pub letter: char, + pub letter: char +} + +impl Hand { + pub fn score(&self) -> i32 { + match self.letter { + 'A' => 1, + 'B' => 2, + 'C' => 3, + 'X' => 1, + 'Y' => 2, + 'Z' => 3, + _ => panic!("Unknown hand {}", self.letter) + } + } + + pub fn outcome(&self, other: &Hand) -> i32 { + match self.score() - other.score() { + -1 => 0, + -2 => 6, + 0 => 3, + 1 => 6, + 2 => 0, + _ => panic!("Unknown match {} vs {}", self.letter, other.letter) + } + } + + pub fn outcome_b(&self) -> i32 { + match self.letter { + 'X' => 0, + 'Y' => 3, + 'Z' => 6, + _ => panic!("Unknown outcome {}", self.letter) + } + } + + pub fn for_outcome(&self, enemy: &Hand) -> Self { + let letter = match (self.outcome_b(), enemy.letter) { + (o, l) if o == 3 => l, + (o, l) if o == 0 && l == 'A' => 'C', + (o, l) if o == 0 && l == 'B' => 'A', + (o, l) if o == 0 && l == 'C' => 'B', + (o, l) if o == 6 && l == 'A' => 'B', + (o, l) if o == 6 && l == 'B' => 'C', + (o, l) if o == 6 && l == 'C' => 'A', + (o, l)=> panic!("Unknown pairing {}/{}", o, l) + }; + Self { + letter + } + } } struct Round { - enemy: Hand, - me: Hand, + pub enemy: Hand, + pub me: Hand, +} + +impl Round { + pub fn score(&self) -> i32 { + self.me.score() + self.me.outcome(&self.enemy) + } + + pub fn score_b(&self) -> i32 { + let me = self.me.for_outcome(&self.enemy); + me.score() + self.me.outcome_b() + } } pub fn run() { let input = read("02"); - let lines = input.lines().map(|l| { + let rounds = input.lines().map(|l| { let hands = l.split(' ').collect::>(); Round { enemy: Hand { @@ -21,17 +82,24 @@ pub fn run() { letter: hands[1].chars().next().unwrap(), }, } - }); + } + ).collect::>(); #[cfg(feature = "part1")] { - let a = "TODO"; + let a: i32 = rounds + .iter() + .map(|r|r.score()) + .sum(); eprintln!("Day 2, Part 01: {}", a); } #[cfg(feature = "part2")] { - let b = "TODO"; + let b: i32 = rounds + .iter() + .map(|r|r.score_b()) + .sum(); eprintln!("Day 2, Part 02: {}", b); } }