Bob Newhart Bob Newhart - 11 months ago 42
C++ Question

Equal elements in an unsorted array

I am making a program to identify whether a 5 card ( user input ) array is a certain hand value. Pair, two pair, three of a kind, straight, full house, four of a kind ( all card values are ranked 2-9, no face cards, no suit ). I am trying to do this without sorting the array. I am currently using this to look through the array and identify if two elements are equal to each other

bool pair(const int array[])
for (int i = 0; i < array; i++)
if (array[i]==aray[i+1])
return true;
return false;

Does this section of code only evaluate whether the first two elements are the same, or will it return true if any two elements are the same? I.E if the hand entered were 2,3,2,4,5 would this return false, where 2,2,3,4,5 would return true? If so, how do I see if any two elements are equal, regardless of order, without sorting the array?

edit: please forgive the typos, I'm leaving the original post intact, so as not to create confusion.

I was not trying to compile the code, for the record.

Ben Ben
Answer Source

It will do neither:

  1. i < array will not work, array is an array not an int. You need something like int arraySize as a second argument to the function.
  2. Even if you fix that then this; array[i]==aray[i+1] will cause undefined behaviour because you will access 1 past the end of the array. Use the for loop condition i < arraySize - 1.
  3. If you fix both of those things then what you are checking is if 2 consecutive cards are equal which will only work if the array is sorted.

If you really cant sort the array (which would be so easy with std::sort) then you can do this:

bool hasPair(const int array[], const int arraySize) {
    const int NumCards = 9
    int possibleCards[NumCards] = {0};
    for (int i = 0; i < arraySize; i++) {
       possibleCards[array[i]]++; // Increment the card so that you 
                                  // count how many of each card is in your hand.
    for (int i = 0; i < NumCards; ++i) {
        // If you want to check for a pair or above.
        if (possibleCards[i] >= 2) { return true; }
        // If you want to check for exactly a pair.
        if (possibleCards[i] == 2) { return true; }
    return false;