1
0
Fork 0

Added RockPaperScissors implementation/Enum and hashmaps.

This commit is contained in:
Yohan Boujon 2023-10-11 13:51:17 +02:00
parent b281043fec
commit 7c722de821
2 changed files with 27 additions and 6 deletions

View file

@ -1,10 +1,13 @@
use crate::rps::get_converter;
use std::collections::HashMap; use std::collections::HashMap;
mod rps; mod rps;
fn main() fn main()
{ {
let converter : HashMap<char, rps::RockPaperScissors> = rps::get_converter(); let converter : HashMap<char, rps::RockPaperScissors> = rps::get_converter();
println!("Hello world!"); let player = converter.get(&'Y').unwrap().battle(converter.get(&'A').unwrap());
println!("First battle = {}", player);
let player = converter.get(&'X').unwrap().battle(converter.get(&'B').unwrap());
println!("Second battle = {}", player);
let player = converter.get(&'Z').unwrap().battle(converter.get(&'C').unwrap());
println!("Third battle = {}", player);
} }

View file

@ -1,9 +1,19 @@
use std::collections::HashMap; use std::collections::HashMap;
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub enum RockPaperScissors { pub enum RockPaperScissors {
Rock, Rock = 0,
Paper, Paper = 1,
Scissors Scissors = 2
}
impl RockPaperScissors{
pub fn battle(&self, other: &RockPaperScissors) -> u64
{
let weight = get_weight();
let tab = weight.get(&self).unwrap();
(*self as u64) + 1 + (tab[*other as usize] as u64)
}
} }
pub fn get_converter() -> HashMap<char, RockPaperScissors> { pub fn get_converter() -> HashMap<char, RockPaperScissors> {
@ -15,4 +25,12 @@ pub fn get_converter() -> HashMap<char, RockPaperScissors> {
('Y', RockPaperScissors::Paper), ('Y', RockPaperScissors::Paper),
('Z', RockPaperScissors::Scissors), ('Z', RockPaperScissors::Scissors),
]) ])
}
fn get_weight() -> HashMap<RockPaperScissors, [u8; 3]> {
HashMap::from([
(RockPaperScissors::Rock, [3,0,6]),
(RockPaperScissors::Paper, [6,3,0]),
(RockPaperScissors::Scissors, [0,6,3]),
])
} }