From 23046cc5aa9e99d344d91319728703bf5720e7c3 Mon Sep 17 00:00:00 2001 From: nalydmerc Date: Sat, 23 Mar 2024 11:30:24 -0400 Subject: [PATCH] Finish tests for different hands --- src/hand.rs | 69 ++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 61 insertions(+), 8 deletions(-) diff --git a/src/hand.rs b/src/hand.rs index ca462d0..7eff4f3 100644 --- a/src/hand.rs +++ b/src/hand.rs @@ -22,11 +22,11 @@ struct PokerHand { impl fmt::Display for PokerHand { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let s = match self.hand_type() { - HandType::HighCard => write!(f, "{}", self.cards[4]), + HandType::HighCard => write!(f, "{}", self.card_str()), HandType::OnePair => { for val in self.hash_map() { if val.1 == 2 { - return write!(f, "Pair of {:?}'s", val); + return write!(f, "{} | Pair of {:?}'s", self.card_str(), val); } } return write!(f, "???"); @@ -51,6 +51,16 @@ impl PokerHand { PokerHand { cards } } + fn card_str(&self) -> String { + let mut cardstr: String = "".to_owned(); + for card in &self.cards { + cardstr.push_str(&card.to_string()); + cardstr.push(' '); + } + + cardstr + } + fn hash_map(&self) -> HashMap { let mut count: HashMap = HashMap::new(); @@ -150,25 +160,68 @@ fn is_four_of_a_kind(hand: &PokerHand) -> bool { } fn is_full_house(hand: &PokerHand) -> bool { - false + let map = hand.hash_map(); + if map.len() != 2 { + return false; + } + + let count: Vec = map.into_values().collect(); + + // https://stackoverflow.com/questions/45353757/how-to-count-the-elements-in-a-vector-with-some-value-without-looping + if count.iter().filter(|&n| *n == 2).count() != 1 { + return false; + } + + if count.iter().filter(|&n| *n == 2).count() != 1 { + return false; + } + + true } fn is_flush(hand: &PokerHand) -> bool { - false + let suit = hand.cards[0].suit; + for card in &hand.cards { + if card.suit != suit { + return false; + } + } + + true } +/// This function relies on the fact that the vector of cards is sotred fn is_straight(hand: &PokerHand) -> bool { - false + let lowest_val = hand.cards[0].value; + + for i in 1..4 { + if (hand.cards[i].value >= lowest_val) { + return false; + } + } + + true } fn is_three_of_a_kind(hand: &PokerHand) -> bool { - false + let map = hand.hash_map(); + let count: Vec = map.into_values().collect(); + + count.contains(&3) } fn is_two_pair(hand: &PokerHand) -> bool { - false + let map = hand.hash_map(); + let count: Vec = map.into_values().collect(); + + // https://stackoverflow.com/questions/45353757/how-to-count-the-elements-in-a-vector-with-some-value-without-looping + count.iter().filter(|&n| *n == 2).count() == 2 } fn is_one_pair(hand: &PokerHand) -> bool { - false + let map = hand.hash_map(); + let count: Vec = map.into_values().collect(); + + // https://stackoverflow.com/questions/45353757/how-to-count-the-elements-in-a-vector-with-some-value-without-looping + count.iter().filter(|&n| *n == 2).count() == 1 }