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

1
2
3
4
5
6
int main()
{
   srand(time(NULL)); //Initialises randomiser or sum' like that
   int x=rand%10;      //Generates from 0-9
   cout<<x;
}


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?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <cstdlib>
#include <ctime>
#include <random>
#include <iterator>
#include <iostream>

int random_int( std::mt19937& rng, int low, int high )
{ return std::uniform_int_distribution<int>( 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.