Search code examples
javaprobabilitypoker

Probability to get pair from 5-card hand poker


I need to find a probability percentage to get one pair of cards from 5-card hand by simulation.

So far I've made classes "Card" (functions: card value, suit, comparing to another card by value) and "Hand" (functions: addCard and isOnePair which returns true only if instance of hand has one pair of cards in it).

Card.java:

public enum CardValue { s2, s3, s4, s5, s6, s7, s8, s9, s10, J, Q, K, A }

public enum CardSuit { C, D, H, S }

private CardValue value;
private CardSuit suit;

public Card(CardValue value, CardSuit suit) {
    this.value = value;
    this.suit = suit;
}

@Override
public boolean equals(Object obj) {
    if(obj == this) {
        return true;
    }
    if(!(obj instanceof Card)) {
        return false;
    }
    Card card = (Card)obj;
    return card.value == this.value;
}

Hand.java

private Set<Card> hand;

public Hand() {
    this.hand = new HashSet<>();
}

public void addCard(Card card) {
    this.hand.add(card);
}

@Override
public String toString() {
    return this.hand.toString();
}

private boolean isOnePair() {
    int counter = 0;
    for(Card card : hand){
        for(Card card2 : hand) {
            if(card.equals(card2)) {
                counter++;
            }
        }
        if(counter == 2) {
            return true;
        }
        counter = 0;
    }

    return false;
}

Solution

    • First, create a List deck containing all the possible Cards.
    • Then, for each iteration of your simulation, shuffle the deck and draw the first 5 Cards.
    • Check if there is a pair, if there is, increment a counter.
    • Divide the counter by the total of iteration.

    Example:

    Random rand = new Random();
    
    final int NUMBER_OF_VALUES = Card.CardValue.values().length;
    final int NUMBER_OF_SUITS = Card.CardSuit.values().length;
    final int NUMBER_OF_CARDS_IN_HAND = 5;
    Card.CardValue value;
    Card.CardSuit suit;
    Hand hand;
    List<Card> deck = new ArrayList<>();
    
    // Deck creation
    for(int i = 0; i < NUMBER_OF_VALUES; i++) {
        for(int j = 0; j <  NUMBER_OF_SUITS; j++)
            deck.add(new Card(Card.CardValue.values()[i], Card.CardSuit.values()[j]));
    }
    
    int counter = 0;
    final int TOTAL = 100000;
    
    // Simulation
    for(int i = 0; i < TOTAL; i++) {
        Collections.shuffle(deck);
        hand = new Hand();
        for(int j = 0; j < NUMBER_OF_CARDS_IN_HAND; j++)
            hand.addCard(deck.get(j));
        if(hand.isOnePair()) counter++;
    }
    
    System.out.println("Probability: " + 100 * counter / (double)TOTAL + "%");