1
0

Working great ! :D

This commit is contained in:
Pcornat 2022-12-04 20:59:06 +01:00
parent f9ca1c15f0
commit da873ef463
Signed by: Pcornat
GPG Key ID: 2F3932FF46D9ECA0
4 changed files with 57 additions and 2 deletions

View File

@ -1,2 +1,4 @@
extern crate core;
pub mod prob1; pub mod prob1;
pub mod prob2; pub mod prob2;

View File

@ -5,6 +5,6 @@ fn main() {
let file_path = args let file_path = args
.get(1) .get(1)
.expect("Please provide an argument on command-line."); .expect("Please provide an argument on command-line.");
let max = prob2::solve_part1(file_path); let max = prob2::solve_part2(file_path);
println!("{max}"); println!("{max}");
} }

View File

@ -5,6 +5,7 @@ pub enum Play {
Scissors, Scissors,
} }
#[derive(Copy, Clone)]
enum ResultPlay { enum ResultPlay {
Win, Win,
Draw, Draw,
@ -97,6 +98,41 @@ pub fn round_score(play: char, counter_play: char) -> i32 {
} }
} }
fn choose_answer(strat: &ResultPlay, input: Play) -> Play {
use Play::*;
use ResultPlay::*;
match strat {
Loss => match input {
Rock => Scissors,
Paper => Rock,
Scissors => Paper,
},
Draw => input,
Win => match input {
Rock => Paper,
Paper => Scissors,
Scissors => Rock,
},
}
}
fn getting_score(game_output: &ResultPlay, play: Play) -> i32 {
let game: i32 = (*game_output).into();
let play_result: i32 = play.into();
game + play_result
}
pub fn second_strat(play: char, strat: char) -> i32 {
let coup = Play::from(play);
let response = match strat {
'X' => ResultPlay::Loss,
'Y' => ResultPlay::Draw,
'Z' => ResultPlay::Win,
other => panic!("Wrong letter {other}"),
};
getting_score(&response, choose_answer(&response, coup))
}
pub fn solve_part1(file_path: &str) -> i32 { pub fn solve_part1(file_path: &str) -> i32 {
let contents = let contents =
std::fs::read_to_string(file_path).expect("Please provide a text file as an argument."); std::fs::read_to_string(file_path).expect("Please provide a text file as an argument.");
@ -113,3 +149,20 @@ pub fn solve_part1(file_path: &str) -> i32 {
.iter() .iter()
.sum() .sum()
} }
pub fn solve_part2(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 mut line_iter = line.chars();
let first: char = line_iter.next().unwrap_or('R');
let last: char = line_iter.last().unwrap_or('R');
second_strat(first, last)
})
.collect::<Vec<i32>>()
.iter()
.sum()
}