Search code examples
javaarraylistpoker

Texas Hold 'em recognizing one pair


I'm having trouble with my program recognizing a one pair ONLY AFTER it first checks for a two pair. When checking for the one pair first it finds it ok. But when I check for the two pair first then check for a one pair it doesn't find it. Any help would be appreciated.

package card.game.simulator;

import java.util.ArrayList;

public class RankingUtility {
private RankingEnum rank;

public String getRankOfHand(ArrayList<Card> hand) {
    System.out.printf("%s\n", hand.toString());
    ArrayList<Card> rankingCards = getTwoPair(hand);
    if(rankingCards != null) {
        return "Two Pair!";
    }
    System.out.printf("%s\n", hand.toString());
    rankingCards = getOnePair(hand);
    if(rankingCards != null) {
        return "One Pair!";
    }
    System.out.printf("%s\n", hand.toString());
    return "You got nuthin...";
}

public boolean isSameSuit(ArrayList<Card> hand) {
    CardSuitEnum suit = hand.get(0).getSuit();
    for(Card card : hand) {
        if(card.getSuit() != suit) {
            return false;
        }
    }
    return true;
}

public ArrayList<Card> checkPair(ArrayList<Card> hand) {
    ArrayList<Card> checkedPair = new ArrayList<>();
    for(Card card1 : hand) {
        checkedPair.add(card1);
        for(Card card2 : hand) {
            if(!card1.equals(card2) && card1.getFace().equals(card2.getFace())) {
                checkedPair.add(card2);
                return checkedPair;
            }
        }
        checkedPair.clear();
    }
    return null;
}

public ArrayList<Card> getTwoPair(ArrayList<Card> hand) {
    ArrayList<Card> twoPair = new ArrayList<>();
    ArrayList<Card> checkedPair = checkPair(hand);
    if(checkedPair != null) {
        twoPair.addAll(checkedPair);
        hand.removeAll(checkedPair);
    }
    checkedPair = checkPair(hand);
    if(checkedPair != null) {
        twoPair.addAll(checkedPair);
        return twoPair;
    }
    return null;
}

public ArrayList<Card> getOnePair(ArrayList<Card> hand) {
    return checkPair(hand);
}
}

Solution

  • When you run getTwoPair the first operation you do is checkPair(hand); This finds the pair (the one you want) removes it, then tries to check again. When this check fails, it returns.

    After the return you're left with (1) a hand that has the pair removed and (2) a null return from getTwoPair. This result leaves you with a condition that causes the main flow to continue, yet fail on finding the single pair, since it was removed.

    I suggest making a copy of the array list to search on. If you fail to find two pairs, simply return the original array. If you find tow pairs, return the modified array.