Cmi
Cmi

Reputation: 489

Why am I getting duplicates in my array?

So I am making an array of 52 ints, I add in random numbers and make sure there all different. If there is a duplicate I would generate a new number so that current index that am at is different. Where am I going wrong?

for(i=0; i < SIZE; i++){

    deck[i] = (rand() % 52);

    for(c= 0; c <= i; c++ ){
            if(deck[c] == deck[i+1]){

            deck[i] = (rand() % 52);
        }

    }
}

Upvotes: 1

Views: 61

Answers (2)

Lee Daniel Crocker
Lee Daniel Crocker

Reputation: 13171

Totally the wrong approach. You don't want random numbers; you want precisely the numbers 0 to 51, in random order. To do this, fill the array with the values 0..51, and then shuffle it properly:

for (int i = 0; i < 52; i += 1) deck[i] = i;
for (int i = 52; i > 1; i -= 1) {
    int j = rand() % i;
    int temp = deck[j];
    deck[j] = deck[i-1];
    deck[i-1] = temp;
}

Upvotes: 2

Matt Gregory
Matt Gregory

Reputation: 8652

You can't try merely once for the random number in your inner for loop. After you generate it, you have to check all the previously generated items again to make sure you didn't generate the same random number as another item. This would do the trick (assuming SIZE = 52):

for(i=0; i < SIZE; i++){
    deck[i] = (rand() % SIZE);
    for(c= 0; c < i; c++ ){
        if(deck[c] == deck[i]){
            // Try another number
            i--;
            break;
        }
    }
}

That said, it's not a very fast solution (it could potentially never end). It's better to create an array of numbers 0 to 51 and then shuffle them by swapping two elements at a time. I'm not going to write that for you, but it's a standard way of doing it.

Upvotes: 3

Related Questions