Jerry
Jerry

Reputation: 5

Function to find duplicate (2d) cells in a 3d array

int duplicate (int cards[5][4][13])

I have been trying to develop a function (the prototype is above) that loops through a 3d array that holds 5 cards of a hand and the numerical index to a cell that holds a 1 indicating that a card exists is based on the suit (4) and the face (13).

For example if in a hypothetical hand the first card was a seven of clubs its index would be: [1][3][7] where 1 is the card 3 = clubs and 7 = sevens.

I need to loop through all five cards in the hand and find out if there are any two cards that are identical.

I cant figure out how to do this because I could compare the index of the first card to the other four but then the remaining cards wouldnt be compared to each other.

The function returns 1 if there is a duplicate or 0 if not.

I am very confused.

Thanks!

Upvotes: 0

Views: 224

Answers (2)

caf
caf

Reputation: 239071

One way to approach this is to loop over every possible card, and count how many times it appears:

int suit;

for (suit = 0; suit < 4; suit++) {
    int rank;

    for (rank = 0; rank < 13; rank++) {
        int count = 0;
        int card;

        for (card = 0; card < 5; card++) {
            count += cards[card][suit][rank];
        }

        if (count > 1)
            return 1;
    }
}

return 0;

However, the data structure you've chosen isn't very efficient. To find out what card N is, you need to search through all of cards[N][0..3][0..12] to find the 1. A better approach would be to use a struct:

struct card {
    int suit; /* 0..3 */
    int rank; /* 0..12 */
};

struct card cards[5];

This will be a lot easier to work with. For example, to find duplicates, you'd just need to check if any of the other cards had the same rank and suit values:

int card1, card2;

for (card1 = 0; card1 < 5; card1++)
    for (card2 = card1 + 1, card2 < 5; card2++)
        if (cards[card1].suit == cards[card2].suit && cards[card1].rank == cards[card2].rank)
            return 1;
return 0;

Upvotes: 1

SingleNegationElimination
SingleNegationElimination

Reputation: 156188

You seem to be describing a hand which is a collection of 5 (hopefully unique) cards. that means you want 5 objects. But cards[5][4][13] is 260 objects. That would be for a structure with 5 slots, and each slot can contain any quantity of any type of card.

Since I suspect that's what you really want, I'll advise you to change your representation of a hand to int cards[5]. In each position in cards you'll place an integer 0-12 for each card in the suit of hearts, 13-25 for each card in the suit of spades, and so on for clubs and diamonds. If you also need a way to represent no card in that slot, you could use -1.

The checking for duplicates is easy, just compare each integer value in the hand.

Upvotes: 1

Related Questions