2022/src/day02.rs

97 lines
2.4 KiB
Rust

use crate::day02::Move::{Paper, Rock, Scissors};
use crate::utils;
/*
First Colum (Opponent):
A = Rock
B = Paper
C = Scissors
Second Colum (You):
X = Rock
Y = Paper
Z = Scissors
Rock > Scissors
Scissors > Paper
Paper > Rock
Score:
Win -> 6
Draw -> 3
Loos -> 0
Rock (X) -> 1
Paper (Y) -> 2
Scissors (Z) -> 3
*/
#[derive(Clone)]
enum Move {
Rock,
Paper,
Scissors
}
pub fn execute_task01(content: &str) {
let vector = utils::convert_to_string_slice(&content);
let score: i32 = vector.into_iter().map(|line| {
let opp_char: char = line.chars().nth(0).unwrap();
let you_char: char = line.chars().nth(2).unwrap();
calculate_score_from_game(&convert_to_move(opp_char), &convert_to_move(you_char))
}).sum();
println!("Day02 - Task01 - Score: {}", score);
}
pub fn execute_task02(content: &str) {
let vector = utils::convert_to_string_slice(&content);
let score: i32 = vector.into_iter().map(|line| {
let opp_char: char = line.chars().nth(0).unwrap();
let you_char: char = line.chars().nth(2).unwrap();
let opp_move: Move = convert_to_move(opp_char);
calculate_score_from_game(&opp_move, &convert_to_conditional_move(&opp_move ,you_char))
}).sum();
println!("Day02 - Task01 - Score: {}", score);
}
fn convert_to_conditional_move(opp: &Move, you: char) -> Move {
match (you, opp) {
('X', Rock) => Scissors,
('X', Paper) => Rock,
('X', Scissors) => Paper,
('Y', _) => opp.clone(),
('Z', Rock) => Paper,
('Z', Paper) => Scissors,
('Z', Scissors) => Rock,
_ => unreachable!(),
}
}
fn convert_to_move(c: char) -> Move {
match c {
'A' | 'X' => Rock,
'B' | 'Y' => Paper,
'C' | 'Z' => Scissors,
_ => unreachable!(),
}
}
fn calculate_score_from_game(opp: &Move, you: &Move) -> i32 {
match (opp, you) {
(Rock, Rock) => 3 + 1, // You Draw with Rock
(Rock, Paper) => 6 + 2, // You Win with Paper
(Rock, Scissors) => 0 + 3, // You Lose with Scissors
(Paper, Rock) => 0 + 1, // You Lose with Rock
(Paper, Paper) => 3 + 2, // You Draw with Paper
(Paper, Scissors) => 6 + 3, // You Win with Scissors
(Scissors, Rock) => 6 + 1, // You Win with Rock
(Scissors, Paper) => 0 + 2, // You Lose with Paper
(Scissors, Scissors) => 3 + 3, // You Draw with Scissors
}
}