Search code examples
javapoker

Get all possible 5 card poker hands given 7 cards


I'm trying to find the 21 5-card poker hands one can form given a 5-card board and 2 hole cards. Here's what I have so far:

public String[] joinArrays(String[] first, String[] second) {
        String[] result = new String[first.length + second.length];
        for (int i = 0; i < first.length; i++) {
            result[i] = first[i];
        }
        for (int i = 0; i < second.length; i++) {   
            result[i + first.length] = second[i]; 
        }
        return result;
    }

    public String[][] getAllPossibleHands(String[] board, String[] hand){
        String[] allCards = joinArrays(board, hand);
        String[][] allHands = new String[21][5];
        ...
    }

Any hints on where to go from here? I have an array of 7 elements and want to create the 7C5 (21) 5-element arrays form-able from these elements.

Thanks!


Solution

  • For every hand select two of the 7 cards to not use. Add all the others

    int cardsSelected = 0;
    int hand = 0;
    // select first card not to be in the hand
    for(int firstCard = 0; firstCard < 7; firstCard++){
        // select first card not to be in the hand
        for(int secondCard = firstCard + 1; secondCard < 7; secondCard++){
            // every card that is not the first or second will added to the hand
            for(int i = 0; i < 7; i++){
                if(i != firstCard && i != secondCard){
                    allHands[hand][cardsSelected++] = allCards[i];
                }
            }
            // next hand
            cardsSelected = 0;
            hand++;
        }
    }