Saturday, August 27, 2011

Probability by Counting

Related Articles

Poker Probability

Suppose you draw five cards from a shuffled deck, what is the probability of getting a pair ?

Card Representation

Let's represent the five drawn cards in an array of String. For example :
String[] cards = {"S5,"SA","D6","H7","CT"};
Which means the five of Spade, the ace of Spade, the six of Diamond, the seven of Heart and the ten of Club. In the related article section, you may see some practical use of this representation in shuffling and displaying the cards.

Sorting the Cards

if we sort the card array, then it is easy to determined whether it contains a pair. All we have to do is just to compare consecutive cards.
boolean pair=false;
if (samePoint(cards[0],cards[1])) pair=true;
if (samePoint(cards[1],cards[2])) pair=true;
if (samePoint(cards[2],cards[3])) pair=true;
if (samePoint(cards[3],cards[4])) pair=true;

Array sorting is easy and you may see the series of "Sorting in Java" in the related articles section.

You may write four compare statements as above, or you may write a for loop as follows :

boolean pair=false;
for (int i=0;i<cards.length-1;i++)
  if (samePoint(cards[i],cards[i+1])) pair=true;

Strict Definition of a "Pair Pattern"

In the game of poker, typically we don't consider a triple as a pair. We don't consider full house as a pair. We don't consider "two pairs" as a pair. Therefore we must refine the above implementation to handle the following patterns :
AAABCThis is known as a triple and is not considered as a pair
AAABBThis is known as a "full house" and is not considered as a pair
AAAABThis is known as "four of a kind" and is not considered as a pair
AABBCThis is known as "two pairs" and is not considered as a pair
AABCDThis is known as "a pair" and is what we want

Fortunately, it is easier than we think. All we have to do is to ensure there is one and only one pair.

Counting the probability

Just generate all five card combinations out of a deck of 52 cards. If it is pair, increase the counter by one. Then the probability is calculated by :
pair_count / total_combination

Combination generation can be found in the related article section. You should read that article first. A modified version that handles String array is provided as follows :

Testing the combination program

java Combination


S2 S3 S4
S2 S3 S5
S2 S3 S6
S2 S4 S5
S2 S4 S6
S2 S5 S6
S3 S4 S5
S3 S4 S6
S3 S5 S6
S4 S5 S6

The Probability Counting Program

We are now going to write a probability counting program with the following output :
javac *.java
java ProbabilityCount

Probability of getting a pair = 1098240/2598960 = 0.4225690276
Probability of getting two pairs = 123552/2598960 = 0.0475390156
Probability of getting three of a kind = 54912/2598960 = 0.0211284514
Probability of getting four of a kind = 624/2598960 = 0.0002400960
Probability of getting full house = 3744/2598960 = 0.0014405762

Source Code

No comments:

Post a Comment