Pergunta

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;
        }
}
Foi útil?

Solução

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.

Outras dicas

There's nothing wrong with your usage of srand. But, the task you describe is very simple, and doesn't involve the use of the rand function.

std::vector<int> v(size);
std::iota(v.begin(), v.end(), 0);
std::random_shuffle(v.begin(), v.end());

If you don't have the iota function, it just generates an incrementing sequence of integers.

Your #includes are not the problem. The problem is: you are not trying to generate alternate numbers when the first one you generate has already been used.

You should include a while loop, inside the for loop, which keeps generating new numbers until you find one that works.

They way it's written now, if you generate the sequence 4,1,4,2,4 for size1 = 5, your array will end up looking like this:

{4,1,0,2,0}

Assuming each entry was set to 0 initially. This is because you will just skip over the indices for which the two extra 4s were generated.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top