-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_random_number.h
More file actions
47 lines (40 loc) · 1.22 KB
/
Copy pathgenerate_random_number.h
File metadata and controls
47 lines (40 loc) · 1.22 KB
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
#ifndef CPP_ALGORITHM_GENERATE_RANDOM_NUMBER_H
#define CPP_ALGORITHM_GENERATE_RANDOM_NUMBER_H
#include <random>
namespace GenerateRandomNumber
{
/**
* \brief Generate a random number in a range with equal probability.
* \param lower_bound lower bound
* \param upper_bound upper bound
* \return result number
*/
int GenerateUniformRandomNumber(
int lower_bound,
int upper_bound);
}
// ----------------------------------------------------------------------------
inline int ZeroOneRandom()
{
std::default_random_engine generator((std::random_device())());
std::uniform_int_distribution<int> distribution(0, 1);
return distribution(generator);
}
// ----------------------------------------------------------------------------
inline int GenerateRandomNumber::GenerateUniformRandomNumber(
const int lower_bound,
const int upper_bound)
{
int result = 0;
const int number_of_outcomes = upper_bound - lower_bound + 1;
do
{
result = 0;
for (int i = 0; (1 << i) < number_of_outcomes; ++i)
{
result = (result << 1) | ZeroOneRandom();
}
} while (result >= number_of_outcomes);
return result + lower_bound;
}
#endif