0

I want to generate numbers between range of 1 to n to create test cases for my program. So i created an array of size n and then stored it in array then usedrandom_shuffle But it's actually not random it always gives same series of number. it changes series like after 3 or 4 shuffling.

So is there any better way to do it. My basic problem is just to create a series of number from [1, n] in any random manner.

int n = 9;

   int arr[9] = {1,2,3,4,5,6,7,8,9};

   int k = 2;

   while(k--)
    random_shuffle(arr, arr+ n);

    for(auto x :arr)
        cout << x <<" ";

Output : 5 4 8 9 1 6 3 2 7 
So for either k = 1 or k = 2 it gives same output.

2 Answers2

2

According to cppreference, std::random_shuffle commonly uses std::rand() as randomizer, which would require setting seed with srand() first.

However, std::shuffle accepts the generators from <random> library (which are superior to rand() unless you are using MinGW older than 9.3)

Example of usage from cppreference (linked above):

#include <random>
#include <algorithm>
#include <iterator>
#include <iostream>

int main()
{
    std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    std::random_device rd;
    std::mt19937 g(rd());

    std::shuffle(v.begin(), v.end(), g);

    std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << "\n";
}
Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52
2

Computers cannot generate true random numbers. Although there are techniques to generate something close to true randomness by for example measuring background radiation, generally random numbers generated by programs are pseudo random numbers.

A pseudo random sequence starting from some state is always identical to another pseudo random sequence starting from the same state, and using the same algorithm. In order to generate a different sequence, you need to start with a different state. The ability to reproduce a random sequence repeatedly is actually quite a useful thing to do in some cases.

In case of std::random_shuffle, the initial state is set with the std::srand function. If you pass a different number to std::srand, then you get a different pseudo random sequence and thus a different shuffle. A typical simple approach is to use the current time of day using std::time function. But take into consideration that the time changes only once every second.

eerorika
  • 232,697
  • 12
  • 197
  • 326