-
Notifications
You must be signed in to change notification settings - Fork 138
/
Copy pathrand_int_fun.cpp
66 lines (60 loc) · 1.95 KB
/
rand_int_fun.cpp
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <random>
#include <iomanip>
#include <string>
// FUNCTION OVERLOAD 1
//-----------------------
// Note: The return type of this function must not be set to std::function<TInt (void)>
// or that will have a performance penalty as this container uses type erasure and heap allocation.
// This function returns lambda or an anonymous callable object, in other words, an object that overloads
// the operator()(), generated by the compiler.
template<typename TInt>
auto make_uniform_random_distribution(TInt a, TInt b, long seed)
{
// std::default_random_engine engine(seed);
std::mt19937 engine(seed);
std::uniform_int_distribution<TInt> dist(a, b);
// std::cout << " [INFO] seed = " << seed << std::endl;
return [=]() mutable -> TInt { return dist(engine); };
}
// FUNCTION OVERLOADING 2
//----------------------------
template<typename TInt>
auto make_uniform_random_distribution(TInt a, TInt b)
{
std::random_device rd;
return make_uniform_random_distribution(a, b, rd()) ;
}
int main()
{
#if 1
std::cout << "\n ===== Random numbers with a random seed ===="
<< std::endl;
{
auto rnd = make_uniform_random_distribution<int>(1, 10);
for(int i = 0; i < 15; i++){
auto field = std::string(" x[") + std::to_string(i) + "] = ";
std::cout << std::setw(10)
<< field
<< std::setw(5) << rnd() << std::endl;
}
}
#endif
std::cout << "\n ===== Random numbers with a non-random seed ===="
<< std::endl;
{
// Initialize Random generator object with known and fixed
// seed to reproduce computation results.
unsigned int seed = 1195785783;
auto rnd = make_uniform_random_distribution<int>(1, 10, seed);
/* Expected sequence: 6, 10, 2, 4, 1, 9, 10, 3, 6, ... */
for(int i = 0; i < 15; i++)
{
auto field = std::string(" x[") + std::to_string(i) + "] = ";
std::cout << std::setw(10)
<< field
<< std::setw(5) << rnd() << std::endl;
}
}
return 0;
}