Skip to content

Commit

Permalink
Add problem 2347: Best Poker Hand
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Nov 30, 2024
1 parent a233679 commit dff419d
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1738,6 +1738,7 @@ pub mod problem_2336_smallest_number_in_infinite_set;
pub mod problem_2337_move_pieces_to_obtain_a_string;
pub mod problem_2341_maximum_number_of_pairs_in_array;
pub mod problem_2342_max_sum_of_a_pair_with_equal_sum_of_digits;
pub mod problem_2347_best_poker_hand;

#[cfg(test)]
mod test_utilities;
60 changes: 60 additions & 0 deletions src/problem_2347_best_poker_hand/brute_force.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl Solution {
fn helper(ranks: &[i32; 5], suits: &[char; 5]) -> &'static str {
let first_suit = suits[0];

if suits[1..].iter().all(|&suit| suit == first_suit) {
return "Flush";
}

let mut counts = [0_u8; 13];
let mut ranks_iter = ranks.iter().copied();

while let Some(rank) = ranks_iter.next() {
let count = &mut counts[(rank as usize).wrapping_sub(1)];

*count += 1;

if *count == 2 {
for rank in ranks_iter {
let count = &mut counts[(rank as usize).wrapping_sub(1)];

if *count == 2 {
return "Three of a Kind";
}

*count += 1;
}

return "Pair";
}
}

"High Card"
}

pub fn best_hand(ranks: Vec<i32>, suits: Vec<char>) -> String {
let (ranks, suits) = Option::zip(ranks.as_slice().try_into().ok(), suits.as_slice().try_into().ok()).unwrap();

Self::helper(ranks, suits).to_string()
}
}

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl super::Solution for Solution {
fn best_hand(ranks: Vec<i32>, suits: Vec<char>) -> String {
Self::best_hand(ranks, suits)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
23 changes: 23 additions & 0 deletions src/problem_2347_best_poker_hand/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
pub mod brute_force;

pub trait Solution {
fn best_hand(ranks: Vec<i32>, suits: Vec<char>) -> String;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
let test_cases = [
(([13, 2, 3, 1, 9], "aaaaa"), "Flush"),
(([4, 4, 2, 4, 4], "daabc"), "Three of a Kind"),
(([10, 10, 2, 12, 9], "abcad"), "Pair"),
(([13, 12, 3, 4, 7], "adcbc"), "High Card"),
];

for ((ranks, suits), expected) in test_cases {
assert_eq!(S::best_hand(ranks.to_vec(), suits.chars().collect()), expected);
}
}
}

0 comments on commit dff419d

Please sign in to comment.