Thread: Comparing elements in an array with eachother

1. Comparing elements in an array with eachother

Hi everyone,
I'm trying to write a program that deals a 5 card poker hand and determines whether or not there is a pair and/or a flush. I have an array hand[] that the cards are dealt into and came up with his loop to see if there is a pair and/or flush. I realized after the first loop it will start comparing values in array positions that don't exist...I know there must be a simpler way of writing this, but I can't figure it out.

Code:
```.....

for (int k = 0; k <= 4; k++) {
if ((hand[k].getValue() == hand[k+1].getValue()) ||
(hand[k].getValue() == hand[k+2].getValue()) ||
(hand[k].getValue() == hand[k+3].getValue()) ||
(hand[k].getValue() == hand[k+4].getValue()))
pair ++;
if ((hand[k].getSuit() == hand[k+1].getSuit()) &&
(hand[k].getSuit() == hand[k+2].getSuit()) &&
(hand[k].getSuit() == hand[k+3].getSuit()) &&
(hand[k].getSuit() == hand[k+4].getSuit()))
flush ++;
}

.....```
Thanks for any help!
-Ryan

2. First, sort the hand, like you do when you really play.
Then you can find pairs and straights easily.

3. So I should sort the array in increasing order, then I can compare the first to the second, second to the third, etc with a loop? as for the flush, the code that I wrote works right?
Thanks

4. Originally Posted by ryanmcclure4
So I should sort the array in increasing order, then I can compare the first to the second, second to the third, etc with a loop?
Yeah, basically...

Originally Posted by ryanmcclure4
as for the flush, the code that I wrote works right?
Thanks
Don't know. Didn't look at it -- [looking] -- Yep, that should do it...

5. Originally Posted by ryanmcclure4
as for the flush, the code that I wrote works right?
No, it has a buffer overrun.
k goes up to 4, and k+4 is then 8.

You should either do this using nested loops where the inner one starts at the value of the outer one, or since I'm sure you've now realised that sorting the hand first may make it easier, just compare the kth card to the k+1th card, with going up to less than 4, with a single loop.

6. Originally Posted by iMalc
No, it has a buffer overrun.
k goes up to 4, and k+4 is then 8.
Ouch! Good catch. I didn't look close enough.

Also, keep in mind that trips (three of a kind) will also register as 3 pairs. And 4 of a kind will be 6 pairs.

One way to handle this is count all the pairs you find. If the count is
1, 2, or 4 you have a pair.
3 or 4 you have trips.