#include <chrono>
#include <iostream>
#include <random>
// Write a function to give you a random number
int random( int min, int max )
{
// Create and initialize our PRNG
staticauto seed = std::chrono::system_clock::now().time_since_epoch().count();
thread_localstatic std::mt19937 prng( seed );
thread_localstaticbool init = true;
if (init) { prng.discard( 10000 ); init = false; }
// Use the PRNG to get a number in the range [min,max]
return std::uniform_int_distribution <int> ( min, max )( prng );
}
// Use the function
int main()
{
int numList[] = { 1, 2, 4, 9, 100, 500 };
int numListCount = 6;
int randFromList = numList[ random( 0, numListCount - 1 ) ];
std::cout << randFromList << "\n";
}
I know that the function to get a random number is a little overwhelming... but it is the Right Thing to do.
(It keeps a different PRNG per thread. It seeds and "warms-up" the PRNG once, before first use. And it gets an unbiased number in the requested range.)
Keep in mind that if you run this program, you will get an evenly-distributed random number from the list; however, if you run the program again you might not. (Initializing the PRNG is not an evenly-distributed random process. PRNGs work best when they exist for a long time -- restarting the program each time you use it defeats that.)
In any case, even in C (using rand()) you should create a function to get a random number. The % remainder trick skews your results.
It' works, sorry, my mistake. I used only a range of two and for coincidence output was always the second number. I had no patiance to wait thinking that the routine was non functioning