Search code examples
c++arraysif-statementfor-loopsrand

What am I doing wrong with srand to build a non repeating random array in C++?


I am trying to build a random array of length (size1). The way that I've researched doing this is to have two separate arrays, one for my random numbers and a secondary "checking" array to make sure the numbers don't repeat. These are labeled (shuffle) and (visit) in my code respectively. count1 is an integer for counting through my for loop.

I have included the following in different combinations and it hasn't worked.

    #include <ctime>
    #include <time.h>
    #include <cstdlib>

The code I seem to be struggling with is this:

    srand((unsigned)time(0));

for (count1 = 0; count1 < size1; count1++)
{
    num = (rand()%size1);
        if (visit[num] == 0)
        {
            visit[num] = 1;
            shuffle[count1] = num;
        }
}

Solution

  • It is easier to fill your array with the numbers 0 to size1-1 and then shuffle those numbers.

    So in c like code (haven't used c in a long time):

    for (int count = 0; count < size1; count++) {
        shuffle[count] = count;
    }
    

    and then shuffle it

    for (int index = 0; index < size1; index++) {
        int shuffleIndex = index + rand() % (size1 - index);
        int temp = shuffle[shuffleIndex];
        shuffle[shuffleIndex] = shuffle[index];
        shuffle[index] = temp;
    }
    

    Basically, for the first element in the array, select any index and switch the values. Now the first index is randomly selected. For the second element, select a random index (excluding the first as that has already been randomly selected) and do the same. Repeat until you get to the last element.