简体   繁体   中英

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);
        }

    }
}

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM