From 7e2195c578850df6913cb1901560f7874bcaf196 Mon Sep 17 00:00:00 2001 From: nalydmerc Date: Sat, 23 Mar 2024 13:15:51 -0400 Subject: [PATCH] * Reorder PokerHand to be sorted highest first + Impliment PartialOrd for OnePair --- src/hand.rs | 49 +++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 45 insertions(+), 4 deletions(-) diff --git a/src/hand.rs b/src/hand.rs index 7eff4f3..362ed87 100644 --- a/src/hand.rs +++ b/src/hand.rs @@ -15,6 +15,7 @@ pub enum HandType { StraightFlush, } +#[derive(PartialEq)] struct PokerHand { cards: Vec, } @@ -44,10 +45,51 @@ impl fmt::Display for PokerHand { } } +impl PartialOrd for PokerHand { + fn partial_cmp(&self, other: &Self) -> Option { + if self.hand_type() > other.hand_type() { + return self.hand_type().partial_cmp(&other.hand_type()); + } + let selfmap = self.hash_map(); + let othermap = other.hash_map(); + match self.hand_type() { + HandType::HighCard => { + // Compare high cards + self.cards.partial_cmp(&other.cards) + } + HandType::OnePair => { + let selfpair: Vec<(&CardValue, &u8)> = + selfmap.iter().filter(|&p| *p.1 == 2).collect(); + let otherpair: Vec<(&CardValue, &u8)> = + othermap.iter().filter(|&p| *p.1 == 2).collect(); + + let pairvalue = selfpair[0].0; + let otherpairvalue = otherpair[0].0; + + if pairvalue != otherpairvalue { + return pairvalue.partial_cmp(otherpairvalue); + } + + self.cards.partial_cmp(&other.cards) + } + HandType::TwoPair => todo!(), + HandType::ThreeOfAKind => todo!(), + HandType::Straight => todo!(), + HandType::Flush => todo!(), + HandType::FullHouse => todo!(), + HandType::FourOfAKind => todo!(), + HandType::StraightFlush => todo!(), + } + } +} + impl PokerHand { fn new(mut cards: Vec) -> Self { assert!(cards.len() == 5); + + // Sorted highest card first cards.sort_unstable(); + cards.reverse(); PokerHand { cards } } @@ -190,12 +232,11 @@ fn is_flush(hand: &PokerHand) -> bool { true } -/// This function relies on the fact that the vector of cards is sotred fn is_straight(hand: &PokerHand) -> bool { - let lowest_val = hand.cards[0].value; - for i in 1..4 { - if (hand.cards[i].value >= lowest_val) { + let current_card = hand.cards[i].value as u8; + let previous_card = hand.cards[i].value as u8; + if current_card != previous_card - 1 { return false; } }