Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The simplest algorithm for poker hand evaluation

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 write a "naive" algorithm but it requires a lot of code.

I saw also a few poker evaluation libraries, which use hashing and bitwise operations, but they look rather complex.

What is the "cleanest and simplest" algorithm for poker hand evaluation ?

like image 725
Michael Avatar asked Apr 28 '12 13:04

Michael


People also ask

Can any hand beat 4 aces?

When two or more players have four of a kind, the highest four of a kind wins. So, four deuces can't beat any other four of a kind, and four aces can't be beaten by any other four of a kind.

What is the most unbeatable hand in poker?

The royal flush sits atop the poker-hand rankings as the best hand possible. It features five consecutive cards of the same suit in order of value from 10 through to ace.

What is flush Royale?

A royal flush is a flush. This means that all of the cards must be of the same suit. There are a number of different kinds of flushes. Unlike most flushes, in a royal flush, the value of all five cards are completely specified. The cards in one's hand must be a ten, jack, queen, king and ace all of the same suit.


1 Answers

Here is a very short but complete histogram based 5 card poker scoring function in Python (2.x). It will get considerably longer if converted to Java.

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' 
like image 145
dansalmo Avatar answered Sep 28 '22 23:09

dansalmo