Random Numbers

How to Program a C++ function, int bigRand (), that generates non-duplicated big random numbers in the range of 0 .. BIG_RAND_MAX (where the BIG_RAND_MAX is defined as 50,000) at each round of up to 50,000 function calls. In the bigRand() function, you should use static variable to memorize the occurrence of any random
number in the range of 0.. BIG_RAND_MAX -1.
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
28
29
30
31
#include <numeric>
#include <random>
#include <ctime>
#include <algorithm>

int big_rand()
{
    ////////////////////////////////////////////////
    constexpr int BIG_RAND_MAX = 50000 ;
    constexpr int N = BIG_RAND_MAX + 1 ;
    static int cycle[N] ;
    static std::mt19937 twister( std::time(0) ) ;

    // fill up the array cycle with integers 0, 1, 2, ..., BIG_RAND_MAX
    // and shuffle the array randomly
    static bool init_once = ( std::iota( cycle, cycle+N, 0 ),
                              std::shuffle( cycle, cycle+N, twister ),
                              true ) ;
    static int pos = -1 ;
    ////////////////////////////////////////////////

    // return numbers in the randomly shuffled array one by one
    ++pos ;
    if( pos == N )
    {
        std::shuffle( cycle, cycle+N, twister ) ;
        pos = -1 ;
    }

    return cycle[pos] ;
}
Topic archived. No new replies allowed.