diff --git a/src/bin/d2p1.rs b/src/bin/d2p1.rs new file mode 100644 index 0000000..cc83efe --- /dev/null +++ b/src/bin/d2p1.rs @@ -0,0 +1,9 @@ +use aoc22::day2; +use aoc22::util; + +pub fn main() { + let rounds = day2::parse_rounds(&util::parse_input()); + + let score = rounds.iter().map(day2::Round::score).sum::(); + println!("Total score is {}", score); +} diff --git a/src/day2.rs b/src/day2.rs new file mode 100644 index 0000000..ad69daf --- /dev/null +++ b/src/day2.rs @@ -0,0 +1,84 @@ +#[derive(PartialEq, Debug)] +pub enum Choice { + Rock, + Paper, + Scissors, +} + +impl Choice { + pub fn score(&self) -> u32 { + match self { + Choice::Rock => 1, + Choice::Paper => 2, + Choice::Scissors => 3, + } + } +} + +#[derive(Debug)] +pub struct Round { + opponent: Choice, + own: Choice, +} + +pub enum RoundResult { + Win, + Draw, + Loss, +} + +impl Round { + pub fn result(&self) -> RoundResult { + let win = match self.own { + Choice::Rock => Choice::Scissors, + Choice::Paper => Choice::Rock, + Choice::Scissors => Choice::Paper, + }; + + if self.opponent == win { + RoundResult::Win + } else if self.opponent == self.own { + RoundResult::Draw + } else { + RoundResult::Loss + } + } + + pub fn score(&self) -> u32 { + let choice_score = self.own.score(); + let result_score = match self.result() { + RoundResult::Win => 6, + RoundResult::Draw => 3, + RoundResult::Loss => 0, + }; + + choice_score + result_score + } +} + +pub fn parse_choice(choice_str: &str) -> Choice { + match choice_str.chars().next().unwrap() { + 'A' => Choice::Rock, + 'B' => Choice::Paper, + 'C' => Choice::Scissors, + 'X' => Choice::Rock, + 'Y' => Choice::Paper, + 'Z' => Choice::Scissors, + _ => panic!("Unknown choice {}", choice_str), + } +} + +pub fn parse_rounds(input: &String) -> Vec { + let lines = input.lines(); + let mut rounds = Vec::new(); + + for line in lines { + let (opponent, own) = line.split_once(' ').unwrap(); + rounds.push(Round { + opponent: parse_choice(opponent), + own: parse_choice(own), + }); + } + + rounds +} diff --git a/src/lib.rs b/src/lib.rs index d338c7e..8102feb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,2 +1,3 @@ pub mod day1; +pub mod day2; pub mod util;