A Poker Hand Evaluator based on a Pefect Hash Algorithm
Efficiently evaluating a poker hand has been an interesting but challenging problem. Given two different poker hands, how to determine which one is stronger? Or more generally, given one poker hand, can we assign a score to it indicating its strength?
Cactus Kev once gave an answer for a five-card poker hand evaluation. With smart encoding, it ranks each hand to 7462 distinct values.
Still, Kev's solution is specific for a five-card hand. To evaluate a seven-card poker hand (which is more popular because of Texas Hold'em) using Kev's algorithm, one brute force solution is to iterate all 7 choose 5 combination, running his five-card evaluation algorithm 21 times to find the best answer, which is apparently too time-inefficient. Omaha poker would be even more complicated, as it requires picking exactly two cards from four player's cards, and exactly three cards from five community cards. Using brute force, it would take 60 iterations (5 choose 3 multiplied by 4 choose 2) of Kev's 5-card evaluation algorithm.
PH Evaluator is designed for evaluating poker hands with more than 5 cards. Instead of traversing all the combinations, it uses a perfect hash algorithm to get the hand strength from a pre-computed hash table, which only costs very few CPU cycles and considerably small memory (~100kb for the 7 card evaluation). With slight modification, the same algorithm can be also applied to evaluating Omaha poker hands.
This documentation has the description of the underlying algorithm.
The cpp subdirectory has the C/C++ implementation of the algorithm, offering evaluation from 5-card hands to 7-card hands, as well as Omaha poker hands.
One of the latest benchmark report generated by Google Benchmark:
2019-12-16 03:00:19
Running ./benchmark_phevaluator
Run on (2 X 2800.18 MHz CPU s)
CPU Caches:
L1 Data 32 KiB (x1)
L1 Instruction 32 KiB (x1)
L2 Unified 1024 KiB (x1)
L3 Unified 33792 KiB (x1)
Load Average: 1.28, 0.35, 0.12
----------------------------------------------------------------
Benchmark Time CPU Iterations
----------------------------------------------------------------
EvaluateAllFiveCards 62860820 ns 62860223 ns 11
EvaluateAllSixCards 514366522 ns 514348819 ns 1
EvaluateAllSevenCards 3552288120 ns 3552229324 ns 1
EvaluateAllOmahaCards 156347907947 ns 156343037129 ns 1
Number of Hands | Time Used | Hands per Second | Memory Used | |
---|---|---|---|---|
5-card Hands | 2598960 | 62860820 ns | 41 M/s | 426K |
6-card Hands | 20358520 | 514366522 ns | 40 M/s | 426K |
7-card Hands | 133784560 | 3552288120 ns | 38 M/s | 426K |
Omaha Hands | 3679075400 | 156347907947 ns | 23 M/s | 426K |
- The memory is not optimal at this stage. We will keep improving it.
The python subdirectory has the latest python implementation, which is still in active development. Contributions are welcome.
There is a javascript implementation using the same algorithm.