-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
uniform_random_number.cc
62 lines (54 loc) · 2.06 KB
/
uniform_random_number.cc
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
#include <functional>
#include <random>
#include <vector>
#include "test_framework/generic_test.h"
#include "test_framework/random_sequence_checker.h"
#include "test_framework/timed_executor.h"
using std::bind;
using std::default_random_engine;
using std::random_device;
using std::uniform_int_distribution;
using std::vector;
int ZeroOneRandom() {
default_random_engine gen((random_device())());
uniform_int_distribution<int> dis(0, 1);
return dis(gen);
}
int UniformRandom(int lower_bound, int upper_bound) {
int number_of_outcomes = upper_bound - lower_bound + 1, result;
do {
result = 0;
for (int i = 0; (1 << i) < number_of_outcomes; ++i) {
// ZeroOneRandom() is the provided random number generator.
result = (result << 1) | ZeroOneRandom();
}
} while (result >= number_of_outcomes);
return result + lower_bound;
}
bool UniformRandomRunner(TimedExecutor& executor, int lower_bound,
int upper_bound) {
using namespace test_framework;
vector<int> result;
executor.Run([&] {
std::generate_n(back_inserter(result), 100000,
std::bind(UniformRandom, lower_bound, upper_bound));
});
vector<int> sequence;
std::transform(begin(result), end(result), back_inserter(sequence),
[lower_bound](int result) { return result - lower_bound; });
return CheckSequenceIsUniformlyRandom(result, upper_bound - lower_bound + 1,
0.01);
}
void UniformRandomWrapper(TimedExecutor& executor, int lower_bound,
int upper_bound) {
RunFuncWithRetries(
bind(UniformRandomRunner, std::ref(executor), lower_bound, upper_bound));
}
int main(int argc, char* argv[]) {
std::vector<std::string> args{argv + 1, argv + argc};
std::vector<std::string> param_names{"executor", "lower_bound",
"upper_bound"};
return GenericTestMain(args, "uniform_random_number.cc",
"uniform_random_number.tsv", &UniformRandomWrapper,
DefaultComparator{}, param_names);
}