Generating Random Integers

closed account (L0Shb7Xj)
I know this has been asked here many times before, but anyway...

I'm creating a game in C++ and need to generate random numbers. I know about

 ``123456`` ``````int main() { srand(time(NULL)); //Initialises randomiser or sum' like that int x=rand%10; //Generates from 0-9 cout<

Now, I need the best way to generate random numbers. Do I call "srand(time(NULL));" every time I want to randomise? What is the best method to generate a nearly perfect random number?

Please note, I may need to call a randomiser more than once a second, so taking second as seed (I believe that's what srand(time(NULL)); does).

Any help would be greatly appreciated.
> Do I call "srand(time(NULL));" every time I want to randomise?

No. See: http://www.cplusplus.com/forum/beginner/103924/

> What is the best method to generate a nearly perfect random number?

True randomness: See if there is a usable `std::std::random_device`

For a game, `std::mt19937` should be adequate.

See: http://www.cplusplus.com/forum/general/103548/#msg557891
closed account (L0Shb7Xj)
So, how do I use it? Can you give me a sample code for generating a number from 0-9?
 ``123456789101112131415161718192021222324252627`` ``````#include #include #include #include #include int random_int( std::mt19937& rng, int low, int high ) { return std::uniform_int_distribution( low, high )(rng) ; } int main() { // initialize random number generator with warm-up sequence // somewhat elaborate because: 'nearly perfect pseudo random numbers' std::srand( std::time(nullptr) ) ; std::uint32_t r[ std::mt19937::state_size ] ; for( std::uint32_t& n : r ) n = std::rand() ; std::seed_seq sseq( std::begin(r), std::end(r) ) ; std::mt19937 gen(sseq) ; // generate and print out 20 random numbers in [0,9] for( int i = 0 ; i < 20 ; ++i ) std::cout << random_int( gen, 0, 9 ) << ' ' ; std::cout << '\n' ; // generate and print out 10 random numbers in [55,72] for( int i = 0 ; i < 10 ; ++i ) std::cout << random_int( gen, 55, 72 ) << ' ' ; std::cout << '\n' ; }``````

http://ideone.com/vV48D9
Topic archived. No new replies allowed.