diff --git a/prob2_part2.txt b/prob2_part2.txt index b457f04..0829cce 100644 --- a/prob2_part2.txt +++ b/prob2_part2.txt @@ -2497,4 +2497,4 @@ C Y B X A Y C Y -B X +B X \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index 7f30432..93e4c65 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,2 +1,4 @@ +extern crate core; + pub mod prob1; pub mod prob2; \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 2ab289a..b8f7cc0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,6 +5,6 @@ fn main() { let file_path = args .get(1) .expect("Please provide an argument on command-line."); - let max = prob2::solve_part1(file_path); + let max = prob2::solve_part2(file_path); println!("{max}"); } diff --git a/src/prob2/mod.rs b/src/prob2/mod.rs index c960b2a..923e091 100644 --- a/src/prob2/mod.rs +++ b/src/prob2/mod.rs @@ -5,6 +5,7 @@ pub enum Play { Scissors, } +#[derive(Copy, Clone)] enum ResultPlay { Win, 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 { let contents = 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() .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::>() + .iter() + .sum() +}