From 1a8b4df940c1dc98760f6c7274601f9552c26fab Mon Sep 17 00:00:00 2001 From: Joscha Date: Fri, 2 Dec 2022 13:23:48 +0100 Subject: [PATCH] [rs] Solve 2022_02 part 1 --- rs/src/main.rs | 2 ++ rs/src/y2022.rs | 1 + rs/src/y2022/d02.rs | 55 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 58 insertions(+) create mode 100644 rs/src/y2022/d02.rs diff --git a/rs/src/main.rs b/rs/src/main.rs index f041859..54baece 100644 --- a/rs/src/main.rs +++ b/rs/src/main.rs @@ -38,6 +38,7 @@ impl Day { days! { Y2022D01: "2022_01", + Y2022D02: "2022_02", } #[derive(Parser)] @@ -71,6 +72,7 @@ fn main() -> anyhow::Result<()> { let input = fs::read_to_string(file)?; match day { Day::Y2022D01 => y2022::d01::solve(input)?, + Day::Y2022D02 => y2022::d02::solve(input)?, } } diff --git a/rs/src/y2022.rs b/rs/src/y2022.rs index 5571216..55e411a 100644 --- a/rs/src/y2022.rs +++ b/rs/src/y2022.rs @@ -1 +1,2 @@ pub mod d01; +pub mod d02; diff --git a/rs/src/y2022/d02.rs b/rs/src/y2022/d02.rs new file mode 100644 index 0000000..e08068a --- /dev/null +++ b/rs/src/y2022/d02.rs @@ -0,0 +1,55 @@ +#[derive(Clone, Copy, PartialEq, Eq)] +enum Choice { + Rock, + Paper, + Scissors, +} + +impl Choice { + fn score_against(self, other: Self) -> u32 { + use self::Choice::*; + + (match self { + Rock => 1, + Paper => 2, + Scissors => 3, + } + match (self, other) { + (Rock, Paper) | (Paper, Scissors) | (Scissors, Rock) => 0, + (Rock, Rock) | (Paper, Paper) | (Scissors, Scissors) => 3, + (Rock, Scissors) | (Paper, Rock) | (Scissors, Paper) => 6, + }) + } +} + +fn read_round(line: &str) -> (Choice, Choice) { + let elems = line.split(' ').take(2).collect::>(); + let l = match elems[0] { + "A" => Choice::Rock, + "B" => Choice::Paper, + "C" => Choice::Scissors, + _ => panic!(), + }; + let r = match elems[1] { + "X" => Choice::Rock, + "Y" => Choice::Paper, + "Z" => Choice::Scissors, + _ => panic!(), + }; + (l, r) +} + +pub fn solve(input: String) -> anyhow::Result<()> { + let choices = input + .lines() + .map(|l| read_round(l.trim())) + .collect::>(); + + // Part 1 + let score = choices + .iter() + .map(|(l, r)| r.score_against(*l)) + .sum::(); + println!("Part 1: {score}"); + + Ok(()) +}