algorithm to check for pair in 5-card poker hand ?

Hi, what is the correct algorithm to check for a pair in a 5 card poker hand?

Here is what i got:
1
2
if (cardValue[0] == cardValue[1] || cardValue[0] == cardValue[2] || cardValue[0] == cardValue[3] || cardValue[0] == cardValue[4] || cardValue[1] == cardValue[2] || cardValue[1] == cardValue[3] || cardValue[1] == cardValue[4] || cardValue[2] == cardValue[3] || cardValue[2] == cardValue[4] || cardValue[3] == cardValue[4]) {
				++pair;

im not sure if this is the correct way. Im comparing each card to each other to see if they are equal.

cardValue[] represents 5 values of 5 cards
Last edited on
If you're limited to just loops and control statements, I would probably make it something similar to

1
2
3
4
5
6
bool pair = false;
for ( unsigned int cardIndex = 0; cardIndex < 5; ++cardIndex )
{
    if ( cardValue[0] == cardValue[cardIndex] || cardValue[1] == cardValue[cardIndex+1] || // etc.
        pair = true;
}
To find out if it is correct test it!!

Probably I would simply count how many times each type occurs and from the resulting list work out the type of hand being held.

In the example below it looks for one pair or four of a kind.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>

using namespace std;

int cardCount[12];
int cardValue[5];
int pairs = 0;
string cardName[12] = {"ace","two","three","four","five","six","seven","eight","nine","jack","queen","king"};

int main()
{

    for (int i=0;i<5;i++)
    {
        cout << "Enter next number  0 to 12: " << endl;
        cin  >> cardValue[i];
    }

    for (int i=0;i<5;i++)
    {
        cardCount[cardValue[i]] = cardCount[cardValue[i]] + 1;  // count how many of each type
    }

    for (int i=0;i<12; i++)
    {
        if (cardCount[i] != 0)
        {
            cout << "There are " << cardCount[i] << " of type " << cardName[i] << endl;
            if (cardCount[i] == 2)
                cout << "one pair of " << cardName[i] << endl;
            if (cardCount[i] == 4)
                cout << "four of a kind " << cardName[i] << endl;
        }
    }
    return 0;
}
Last edited on
Topic archived. No new replies allowed.