The simplest algorithm for poker hand evaluation

后端 未结 12 995
独厮守ぢ
独厮守ぢ 2020-12-04 12:39

I am thinking about poker hand (5 cards) evaluation in Java. Now I am looking for simplicity and clarity rather than performance and efficiency. I probably can

相关标签:
12条回答
  • 2020-12-04 13:15

    Here's a naive approach to five-card hand comparison that I'm using to help initially populate a lookup table:

    • https://gist.github.com/gdejohn/8293321#file-hand-java

    Instead of being as terse as possible, I prioritized type safety and clear, self-documenting code. If you're not familiar with the Guava types I'm using, you can browse their documentation.

    And I'll include the code here (minus static imports for the enum constants at the bottom), although it's really too long to comfortably view in an answer.

    import static com.google.common.base.Preconditions.checkArgument;
    import static com.google.common.collect.Ordering.from;
    import static com.google.common.collect.Ordering.natural;
    import static java.util.Comparator.comparing;
    import static java.util.Comparator.comparingInt;
    
    import java.util.Comparator;
    import java.util.EnumSet;
    import java.util.LinkedList;
    import java.util.Set;
    import java.util.function.Function;
    
    import com.google.common.collect.EnumMultiset;
    import com.google.common.collect.Multiset;
    import com.google.common.collect.Multiset.Entry;
    import com.google.common.collect.Ordering;
    
    public class Hand implements Comparable<Hand> {
        public final Category category;
    
        private final LinkedList<Rank> distinctRanks = new LinkedList<>();
    
        public Hand(Set<Card> cards) {
            checkArgument(cards.size() == 5);
            Set<Suit> suits = EnumSet.noneOf(Suit.class);
            Multiset<Rank> ranks = EnumMultiset.create(Rank.class);
            for (Card card : cards) {
                suits.add(card.suit);
                ranks.add(card.rank);
            }
            Set<Entry<Rank>> entries = ranks.entrySet();
            for (Entry<Rank> entry : byCountThenRank.immutableSortedCopy(entries)) {
                distinctRanks.addFirst(entry.getElement());
            }
            Rank first = distinctRanks.getFirst();
            int distinctCount = distinctRanks.size();
            if (distinctCount == 5) {
                boolean flush = suits.size() == 1;
                if (first.ordinal() - distinctRanks.getLast().ordinal() == 4) {
                    category = flush ? STRAIGHT_FLUSH : STRAIGHT;
                }
                else if (first == ACE && distinctRanks.get(1) == FIVE) {
                    category = flush ? STRAIGHT_FLUSH : STRAIGHT;
                    // ace plays low, move to end
                    distinctRanks.addLast(distinctRanks.removeFirst());
                }
                else {
                    category = flush ? FLUSH : HIGH_CARD;
                }
            }
            else if (distinctCount == 4) {
                category = ONE_PAIR;
            }
            else if (distinctCount == 3) {
                category = ranks.count(first) == 2 ? TWO_PAIR : THREE_OF_A_KIND;
            }
            else {
                category = ranks.count(first) == 3 ? FULL_HOUSE : FOUR_OF_A_KIND;
            }
        }
    
        @Override
        public final int compareTo(Hand that) {
            return byCategoryThenRanks.compare(this, that);
        }
    
        private static final Ordering<Entry<Rank>> byCountThenRank;
    
        private static final Comparator<Hand> byCategoryThenRanks;
    
        static {
            Comparator<Entry<Rank>> byCount = comparingInt(Entry::getCount);
            Comparator<Entry<Rank>> byRank = comparing(Entry::getElement);
            byCountThenRank = from(byCount.thenComparing(byRank));
            Comparator<Hand> byCategory = comparing((Hand hand) -> hand.category);
            Function<Hand, Iterable<Rank>> getRanks =
                    (Hand hand) -> hand.distinctRanks;
            Comparator<Hand> byRanks =
                    comparing(getRanks, natural().lexicographical());
            byCategoryThenRanks = byCategory.thenComparing(byRanks);
        }
    
        public enum Category {
            HIGH_CARD,
            ONE_PAIR,
            TWO_PAIR,
            THREE_OF_A_KIND,
            STRAIGHT,
            FLUSH,
            FULL_HOUSE,
            FOUR_OF_A_KIND,
            STRAIGHT_FLUSH;
        }
    
        public enum Rank {
            TWO,
            THREE,
            FOUR,
            FIVE,
            SIX,
            SEVEN,
            EIGHT,
            NINE,
            TEN,
            JACK,
            QUEEN,
            KING,
            ACE;
        }
    
        public enum Suit {
            DIAMONDS,
            CLUBS,
            HEARTS,
            SPADES;
        }
    
        public enum Card {
            TWO_DIAMONDS(TWO, DIAMONDS),
            THREE_DIAMONDS(THREE, DIAMONDS),
            FOUR_DIAMONDS(FOUR, DIAMONDS),
            FIVE_DIAMONDS(FIVE, DIAMONDS),
            SIX_DIAMONDS(SIX, DIAMONDS),
            SEVEN_DIAMONDS(SEVEN, DIAMONDS),
            EIGHT_DIAMONDS(EIGHT, DIAMONDS),
            NINE_DIAMONDS(NINE, DIAMONDS),
            TEN_DIAMONDS(TEN, DIAMONDS),
            JACK_DIAMONDS(JACK, DIAMONDS),
            QUEEN_DIAMONDS(QUEEN, DIAMONDS),
            KING_DIAMONDS(KING, DIAMONDS),
            ACE_DIAMONDS(ACE, DIAMONDS),
    
            TWO_CLUBS(TWO, CLUBS),
            THREE_CLUBS(THREE, CLUBS),
            FOUR_CLUBS(FOUR, CLUBS),
            FIVE_CLUBS(FIVE, CLUBS),
            SIX_CLUBS(SIX, CLUBS),
            SEVEN_CLUBS(SEVEN, CLUBS),
            EIGHT_CLUBS(EIGHT, CLUBS),
            NINE_CLUBS(NINE, CLUBS),
            TEN_CLUBS(TEN, CLUBS),
            JACK_CLUBS(JACK, CLUBS),
            QUEEN_CLUBS(QUEEN, CLUBS),
            KING_CLUBS(KING, CLUBS),
            ACE_CLUBS(ACE, CLUBS),
    
            TWO_HEARTS(TWO, HEARTS),
            THREE_HEARTS(THREE, HEARTS),
            FOUR_HEARTS(FOUR, HEARTS),
            FIVE_HEARTS(FIVE, HEARTS),
            SIX_HEARTS(SIX, HEARTS),
            SEVEN_HEARTS(SEVEN, HEARTS),
            EIGHT_HEARTS(EIGHT, HEARTS),
            NINE_HEARTS(NINE, HEARTS),
            TEN_HEARTS(TEN, HEARTS),
            JACK_HEARTS(JACK, HEARTS),
            QUEEN_HEARTS(QUEEN, HEARTS),
            KING_HEARTS(KING, HEARTS),
            ACE_HEARTS(ACE, HEARTS),
    
            TWO_SPADES(TWO, SPADES),
            THREE_SPADES(THREE, SPADES),
            FOUR_SPADES(FOUR, SPADES),
            FIVE_SPADES(FIVE, SPADES),
            SIX_SPADES(SIX, SPADES),
            SEVEN_SPADES(SEVEN, SPADES),
            EIGHT_SPADES(EIGHT, SPADES),
            NINE_SPADES(NINE, SPADES),
            TEN_SPADES(TEN, SPADES),
            JACK_SPADES(JACK, SPADES),
            QUEEN_SPADES(QUEEN, SPADES),
            KING_SPADES(KING, SPADES),
            ACE_SPADES(ACE, SPADES);
    
            public final Rank rank;
    
            public final Suit suit;
    
            Card(Rank rank, Suit suit) {
                this.rank = rank;
                this.suit = suit;
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-04 13:15

    If you are representing a hand as an array of, for example, Card objects, then I would have methods for looping through this array and determining if it has a 2-of-a-kind, flush etc - and if it does, what type it is; so you could have the 3ofaKind() method return 5 if a hand had three 5s. Then I would establish a hierarchy of possibilities (e.g. 3 of a kind is higher than 2 of a kind) and work from there. The methods themselves should be pretty straightforward to write.

    0 讨论(0)
  • 2020-12-04 13:16

    Lookup tables are the most straightforward and simplest solution to the problem, and also the fastest. The trick is managing the size of the table and keeping the mode of use simple enough to process very quickly (space–time tradeoff). Obviously, in theory you could just encode each hand that could be held and have an array of evaluations, then --poof-- one table lookup and you are done. Unfortunately, such a table would be huge and unmanageable for most machines, and would invariably have you thrashing disks anyway as memory gets swapped out lots.

    The so-called two-plus-two solution sports a big 10M table, but literally involves one table lookup for each card in the hand. You are not likely to find a faster and simpler to understand algorithm.

    Other solutions involve more compressed tables with more complex indexing, but they are readily comprehensible and pretty fast (although much slower than 2+2). This is where you see language concerning hashing and so forth -- tricks to reduce a table size to more manageable sizes.

    In any case, lookup solutions are orders of magnitude faster than the histogram-sort-dance-on-your-head-compare-special-case-and-by-the-way-was-it-a-flush solutions, almost none of which are worthy of a second glance.

    0 讨论(0)
  • 2020-12-04 13:20
     public class Line
    {
        private List<Card> _cardsToAnalyse;
    
        public Line()
        {
            Cards = new List<Card>(5);
        }
    
        public List<Card> Cards { get; }
    
    
        public string PriceName { get; private set; }
    
    
        public int Result()
        {
            _cardsToAnalyse = Cards;
            var valueComparer = new CardValueComparer();
    
    
            _cardsToAnalyse.Sort(valueComparer);
    
            if (ContainsStraightFlush(_cardsToAnalyse))
            {
                PriceName = "Straight Flush";
                return PayTable.StraightFlush;
            }
    
            if (ContainsFourOfAKind(_cardsToAnalyse))
            {
                PriceName = "Quadra";
                return PayTable.FourOfAKind;
            }
    
            if (ContainsStraight(_cardsToAnalyse))
            {
                PriceName = "Straight";
                return PayTable.Straight;
            }
    
            if (ContainsFullen(_cardsToAnalyse))
            {
                PriceName = "Full House";
                return PayTable.Fullen;
            }
    
            if (ContainsFlush(_cardsToAnalyse))
            {
                PriceName = "Flush";
                return PayTable.Flush;
            }
    
            if (ContainsThreeOfAKind(_cardsToAnalyse))
            {
                PriceName = "Trinca";
                return PayTable.ThreeOfAKind;
            }
    
            if (ContainsTwoPairs(_cardsToAnalyse))
            {
                PriceName = "Dois Pares";
                return PayTable.TwoPairs;
            }
    
            if (ContainsPair(_cardsToAnalyse))
            {
                PriceName = "Um Par";
                return PayTable.Pair;
            }
    
            return 0;
        }
    
        private bool ContainsFullen(List<Card> _cardsToAnalyse)
        {
            var valueOfThree = 0;
    
            // Search for 3 of a kind
            Card previousCard1 = null;
            Card previousCard2 = null;
    
            foreach (var c in Cards)
            {
                if (previousCard1 != null && previousCard2 != null)
                    if (c.Value == previousCard1.Value && c.Value == previousCard2.Value)
                        valueOfThree = c.Value;
                previousCard2 = previousCard1;
                previousCard1 = c;
            }
    
            if (valueOfThree > 0)
            {
                Card previousCard = null;
    
                foreach (var c in Cards)
                {
                    if (previousCard != null)
                        if (c.Value == previousCard.Value)
                            if (c.Value != valueOfThree)
                                return true;
                    previousCard = c;
                }
    
                return false;
            }
    
            return false;
        }
    
        private bool ContainsPair(List<Card> Cards)
        {
            Card previousCard = null;
    
            foreach (var c in Cards)
            {
                if (previousCard != null)
                    if (c.Value == previousCard.Value)
                        return true;
                previousCard = c;
            }
    
            return false;
        }
    
        private bool ContainsTwoPairs(List<Card> Cards)
        {
            Card previousCard = null;
            var countPairs = 0;
            foreach (var c in Cards)
            {
                if (previousCard != null)
                    if (c.Value == previousCard.Value)
                        countPairs++;
                previousCard = c;
            }
    
            if (countPairs == 2)
                return true;
    
            return false;
        }
    
        private bool ContainsThreeOfAKind(List<Card> Cards)
        {
            Card previousCard1 = null;
            Card previousCard2 = null;
    
            foreach (var c in Cards)
            {
                if (previousCard1 != null && previousCard2 != null)
                    if (c.Value == previousCard1.Value && c.Value == previousCard2.Value)
                        return true;
                previousCard2 = previousCard1;
                previousCard1 = c;
            }
    
            return false;
        }
    
        private bool ContainsFlush(List<Card> Cards)
        {
            return Cards[0].Naipe == Cards[1].Naipe &&
                   Cards[0].Naipe == Cards[2].Naipe &&
                   Cards[0].Naipe == Cards[3].Naipe &&
                   Cards[0].Naipe == Cards[4].Naipe;
        }
    
        private bool ContainsStraight(List<Card> Cards)
        {
            return Cards[0].Value + 1 == Cards[1].Value &&
                   Cards[1].Value + 1 == Cards[2].Value &&
                   Cards[2].Value + 1 == Cards[3].Value &&
                   Cards[3].Value + 1 == Cards[4].Value
                   ||
                   Cards[1].Value + 1 == Cards[2].Value &&
                   Cards[2].Value + 1 == Cards[3].Value &&
                   Cards[3].Value + 1 == Cards[4].Value &&
                   Cards[4].Value == 13 && Cards[0].Value == 1;
        }
    
        private bool ContainsFourOfAKind(List<Card> Cards)
        {
            Card previousCard1 = null;
            Card previousCard2 = null;
            Card previousCard3 = null;
    
            foreach (var c in Cards)
            {
                if (previousCard1 != null && previousCard2 != null && previousCard3 != null)
                    if (c.Value == previousCard1.Value &&
                        c.Value == previousCard2.Value &&
                        c.Value == previousCard3.Value)
                        return true;
                previousCard3 = previousCard2;
                previousCard2 = previousCard1;
                previousCard1 = c;
            }
    
            return false;
        }
    
        private bool ContainsStraightFlush(List<Card> Cards)
        {
            return ContainsFlush(Cards) && ContainsStraight(Cards);
        }
    }
    
    0 讨论(0)
  • 2020-12-04 13:22

    You actually don't need any advanced functions, it can be all done bitwise: (source: http://www.codeproject.com/Articles/569271/A-Poker-hand-analyzer-in-JavaScript-using-bit-math)

    (This one is actually written in JavaScript, but you can evaluate JavaScript from Java if needed, so it shouldn't be a problem. Also, this is as short as it gets, so if even for illustration of the approach...):

    First you split your cards into two arrays: ranks (cs) and suits (ss) and to represent suits, you will use either 1,2,4 or 8 (that is 0b0001, 0b0010,...):

    var J=11, Q=12, K=13, A=14, C=1, D=2, H=4, S=8;
    

    Now here's the magic:

    function evaluateHand(cs, ss) {
        var pokerHands = ["4 of a Kind", "Straight Flush","Straight","Flush","High Card","1 Pair","2 Pair","Royal Flush", "3 of a Kind","Full House"];
    
        var v,i,o,s = 1 << cs[0] | 1 << cs[1] | 1 << cs[2] | 1 << cs[3] | 1 << cs[4];
        for (i = -1, v = o = 0; i < 5; i++, o = Math.pow(2, cs[i] * 4)) {v += o * ((v / o & 15) + 1);}
        v = v % 15 - ((s / (s & -s) == 31) || (s == 0x403c) ? 3 : 1);
        v -= (ss[0] == (ss[1] | ss[2] | ss[3] | ss[4])) * ((s == 0x7c00) ? -5 : 1);
        return pokerHands[v];
    }
    

    Usage:

    evaluateHand([A,10,J,K,Q],[C,C,C,C,C]); // Royal Flush
    

    Now what it does (very briefly) is that it puts 1 into 3rd bit of s when there's a 2, into 4th when there's 3, etc., so for the above example s looks like this:

    0b111110000000000

    for [A,2,3,4,5] it would look like this

    0b100 0000 0011 1100

    etc.

    v uses four bits to record multiple occurencies of same card, so it's 52bits long and if you have three Aces and two kings, its 8 MSB bits look like:

    0111 0011 ...

    The last line then checks for a flush or straight flush or royal flush (0x7c00).

    0 讨论(0)
  • 2020-12-04 13:27

    Python 3 version

    def poker(hands):
        scores = [(i, score(hand.split())) for i, hand in enumerate(hands)]
        winner = sorted(scores , key=lambda x:x[1])[-1][0]
        return hands[winner]
    
    def score(hand):
        ranks = '23456789TJQKA'
        rcounts = {ranks.find(r): ''.join(hand).count(r) for r, _ in hand}.items()
        score, ranks = zip(*sorted((cnt, rank) for rank, cnt in rcounts)[::-1])
        if len(score) == 5:
            if ranks[0:2] == (12, 3): #adjust if 5 high straight
                ranks = (3, 2, 1, 0, -1)
            straight = ranks[0] - ranks[4] == 4
            flush = len({suit for _, suit in hand}) == 1
            '''no pair, straight, flush, or straight flush'''
            score = ([(1,), (3,1,1,1)], [(3,1,1,2), (5,)])[flush][straight]
        return score, ranks
    
     >>> poker(['8C TS KC 9H 4S', '7D 2S 5D 3S AC', '8C AD 8D AC 9C', '7C 5H 8D TD KS'])
     '8C AD 8D AC 9C'
    

    Basically have to replace 1 by (1,) to avoid the int to tuple comparison error.

    0 讨论(0)
提交回复
热议问题