I'm creating a Poker 5-cards Hand Evaluator out of a regular 52-card deck, and evaluate the perfect strategy to take based on a ranked list. Included in this list are possible combinations such as "4 to a Straight Flush", "4 to an Outside Straight", "3 to a Straight Flush" and so on.
This is my card class:
public class Card implements Comparable<Card> {
private char rank;
private char suit;
private int value;
public Card(char rank, char suit, int value) {
this.rank = rank;
this.suit = suit;
this.value = value;
}
Along with some getRank()
, getSuit()
and getValue()
methods. My hand is a Card[]
array of 5 elements.
The cards' value
goes from 2
to 14
, where 2 = '2'
and 14 = 'A'
.
I'm having trouble coming up with a simple algorithm (I've seen implementations using HashMaps and bit masks, but it seems rather complex) to check for the aforementioned combinations, because of all the edge cases and the fact that the A
can be a low Ace. All hands are sorted in descending order before being evaluated ("2C 5C 8S KS QH"
becomes "KS QH 8S 5C 2C"
).
I created a isStraight() function:
private boolean isStraight(Card[] sortedHand) {
if (sortedHand[0].getValue() == sortedHand[1].getValue() - 1
&& sortedHand[1].getValue() == sortedHand[2].getValue() - 1
&& sortedHand[2].getValue() == sortedHand[3].getValue() - 1
&& sortedHand[3].getValue() == sortedHand[4].getValue() - 1
) return true;
// Case where there is a Low Ace
if (sortedHand[0].getValue() == 14) {
if (sortedHand[1].getValue() == 5
&& sortedHand[2].getValue() == 4
&& sortedHand[3].getValue() == 3
&& sortedHand[4].getValue() == 2
) return true;
}
return false;
}
But maybe what would be best would be to generalize and create a function that would return the number of cards missing for a straight (it would return 0 in case of a straight - or even the other way around returning 5), but I'm at a loss on how to do that.
Likewise, I have a isFlush() method:
private boolean isFlush(Card[] sortedHand) {
int sameSuit = 0;
char Suit = sortedHand[0].getSuit();
for (int i = 0; i < sortedHand.length; i++) {
if (sortedHand[i].getSuit() == Suit)
sameSuit++;
}
return sameSuit == 5;
}
but it isn't generalized to return the number of cards missing for a flush.
Any input is greatly appreciated!