-
Notifications
You must be signed in to change notification settings - Fork 138
/
Copy pathRandInt.cpp
97 lines (87 loc) · 2.5 KB
/
RandInt.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/* File: RandInt.cpp
* Author: Caio Rodrigues
* Description: Class for simplification and easy use of C++11 uniform distribution
********************************************************************************/
#include <iostream>
#include <random>
#include <iomanip>
#include <string>
template<typename TInt = int>
class RandInt {
private:
std::random_device m_nextSeed;
unsigned int m_seed;
std::default_random_engine m_engine;
std::uniform_int_distribution<int> m_dist;
public:
using TSeed = long;
// Intialize with a known seed
RandInt(TInt min, TInt max, unsigned int seed)
: m_seed(seed), m_engine(seed), m_dist(min, max)
{
}
// Initialize with a random seed
RandInt(TInt min, TInt max)
: m_nextSeed{},
m_seed(m_nextSeed()),
m_engine(m_seed),
m_dist(min, max)
{
}
TInt Min() const { return m_dist.min(); }
TInt Max() const { return m_dist.max(); }
TSeed Seed() const { return m_seed; }
void Seed(TSeed seed)
{
m_seed = seed;
m_engine.seed(seed);
}
// Set seed to a new random (non-deterministic) value and return it
TSeed NextSeed()
{
m_seed = m_nextSeed();
m_engine.seed(m_seed);
return m_seed;
}
// Get NExt random
TInt operator()()
{
return m_dist(m_engine);
}
};
int main()
{
std::cout << "\n ===== Random numbers with a random seed ===="
<< std::endl;
{
RandInt<int> rnd(1, 10);
std::cout << " => rnd.Seed() = " << rnd.Seed() << std::endl;
std::cout << " => rnd.Min() = " << rnd.Min() << std::endl;
std::cout << " => rnd.Max() = " << rnd.Max() << std::endl;
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;
}
}
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.
long seed = 1195785783;
RandInt<int> rnd(1, 10, seed);
std::cout << " => rnd.Seed() = " << rnd.Seed() << std::endl;
std::cout << " => rnd.Min() = " << rnd.Min() << std::endl;
std::cout << " => rnd.Max() = " << rnd.Max() << std::endl;
/* Expected sequence: 7, 10, 9, 2, 2, 1, 3, 1, 6, 5, 1, 2, 3, 2 ... */
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;
}