93 lines
2.4 KiB
Rust
93 lines
2.4 KiB
Rust
#[derive(PartialEq, Eq)]
|
|
pub enum Play {
|
|
Rock,
|
|
Paper,
|
|
Scissors,
|
|
}
|
|
|
|
enum ResultPlay {
|
|
Win,
|
|
Draw,
|
|
Loss,
|
|
}
|
|
|
|
impl Into<char> for Play {
|
|
fn into(self) -> char {
|
|
match self {
|
|
Play::Rock => 'X',
|
|
Play::Paper => 'Y',
|
|
Play::Scissors => 'Z',
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Into<i32> for Play {
|
|
fn into(self) -> i32 {
|
|
match self {
|
|
Play::Rock => 1,
|
|
Play::Paper => 2,
|
|
Play::Scissors => 3,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl From<char> for Play {
|
|
fn from(letter: char) -> Self {
|
|
match letter {
|
|
'A' => Play::Rock,
|
|
'B' => Play::Paper,
|
|
'C' => Play::Scissors,
|
|
'X' => Play::Rock,
|
|
'Y' => Play::Paper,
|
|
'Z' => Play::Scissors,
|
|
_ => panic!("Only A, B, C, X, Y or Z letters are available."),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Into<i32> for ResultPlay {
|
|
fn into(self) -> i32 {
|
|
match self {
|
|
ResultPlay::Win => 6,
|
|
ResultPlay::Draw => 3,
|
|
ResultPlay::Loss => 0,
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn round_score(play: char, counter_play: char) -> i32 {
|
|
let coup = Play::from(play); // translate to the play
|
|
let counter = Play::from(counter_play); // translate to the play
|
|
if coup == counter {
|
|
(ResultPlay::Draw as i32) + (counter_play as i32)
|
|
} else {
|
|
use Play::*;
|
|
use ResultPlay::*;
|
|
match (&coup, &counter) {
|
|
(Rock, Paper) => (Win as i32) + (counter as i32),
|
|
(Rock, Scissors) => (Loss as i32) + (counter as i32),
|
|
(Paper, Rock) => (Loss as i32) + (counter as i32),
|
|
(Paper, Scissors) => (Win as i32) + (counter as i32),
|
|
(Scissors, Rock) => (Win as i32) + (counter as i32),
|
|
(Scissors, Paper) => (Loss as i32) + (counter as i32),
|
|
_ => panic!("Case not covered, impossible to reach."),
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn solve_part1(file_path: &str) -> i32 {
|
|
let contents =
|
|
std::fs::read_to_string(file_path).expect("Please provide a text file as an argument.");
|
|
let lines: Vec<&str> = contents.split('\n').collect();
|
|
lines
|
|
.iter()
|
|
.map(|line| {
|
|
let first: char = line.chars().nth(0).unwrap_or('R');
|
|
let last: char = line.chars().nth(2).unwrap_or('R');
|
|
round_score(first, last)
|
|
})
|
|
.collect::<Vec<i32>>()
|
|
.iter()
|
|
.sum()
|
|
}
|