0

I have an array of n integers. I need to shuffle the array in some random order multiple times during m iterations of the program.

I mean for each of m iterations, the array of n integers needs to be shuffled .

What I do is that I pass an input and an output array of n integers each with the input containing 1 to n and output contains same numbers but in shuffled order.

However the issue I am getting with my code is that consecutive shuffles collide and return same shuffled array .

like if its

1,54,7,11,13,..... in 1st iteration then even in 2nd and 3rd iterations i get the same order ie 1,54,7,11,13,..... 1,54,7,11,13,.....

and again in 4th iteration a new order appears but repeats for next 2,3 iterations 23,1,4,6,76,11,...... 23,1,4,6,76,11,......

whereas my requirement is that each time the shuffling should be unique. My shuffling function code is pasted below

void ShufflingUtility::randomShuffle(int inputArray[],int size,int returnArray[])
{
       srand(time(0));

       std::random_shuffle(&inputArray[0], &inputArray[size]);
       for(int j=0;j<size;j++)
       {
           returnArray[j] = inputArray[j];
       }
}

Any suggestion to resolve this duplication issue is welcome. Thanks in advance.

Nostalgic
  • 300
  • 1
  • 4
  • 18
  • 1
    Does this answer your question? [srand() — why call it only once?](https://stackoverflow.com/questions/7343833/srand-why-call-it-only-once) – Nathan Pierson May 10 '22 at 15:30
  • 1
    First of all, the `srand` function should be called only *once* in a program, as it resets the seed. That could lead to you using the same sequence multiple calls to `randomShuffle`. Secondly, the [`std::random_shuffle`](https://en.cppreference.com/w/cpp/algorithm/random_shuffle) function was deprecated in the C++14 standard, and removed in the C++17 standard. Use `std::shuffle` instead, together with the new [PRNG functions](https://en.cppreference.com/w/cpp/numeric/random) introduced in C++11. – Some programmer dude May 10 '22 at 15:30
  • If `randomShuffle` executes multiple times within one second, `srand(time(0));` will cause each execution to have the same seed, and therefore produces the same output. – Nathan Pierson May 10 '22 at 15:30
  • Note that the [`std::random_shuffle`](https://en.cppreference.com/w/cpp/algorithm/random_shuffle) overload you are using was deprecated in C++14 and removed in C++17. It should not be used in new code. Consider using the modern [random number generator](https://en.cppreference.com/w/cpp/numeric/random) alternatives. – François Andrieux May 10 '22 at 15:35
  • `srand(time(0));` is your bug. Remember that the resolution of time is 1 second so calling this more than 1 time in the same second should result in the same shuffling. – drescherjm May 10 '22 at 16:08

0 Answers0