-
Notifications
You must be signed in to change notification settings - Fork 0
/
03-random.cc
61 lines (53 loc) · 1.36 KB
/
03-random.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
//
// Program
// Random numbers: Generate random numbers for uniform integer
// distribution using Mersenne twister.
//
// Compile
// g++ -Wall -Wextra -pedantic -std=c++17 -o 03-random 03-random.cc
//
// Execution
// ./03-random
//
#include <iostream>
#include <random>
#include <algorithm>
#include <map>
#include <iomanip>
constexpr int scale = 1000;
constexpr int limit = 100000;
//
// Show historgram
//
static void show_histogram(const std::string& title, const std::map<int, int> &hist) {
std::cout << "--- " << title << " ---" << '\n';
for (auto item: hist) {
std::cout << " " << std::setw(2) << item.first << " " << std::string(item.second/scale, '*') << '\n';
}
}
//
// Entry function
//
int main() {
{
std::map<int, int> hist{};
std::random_device rd {};
std::mt19937 mt(rd()); // Get seed from random_device
std::uniform_int_distribution<int> uid(1, 5);
for (int i = 0; i <= limit; ++i) {
hist[uid(mt)] += 1;
}
show_histogram("uniform_int_distribution with mt19937", hist);
}
{
std::map<int, int> hist{};
std::random_device rd {};
std::mt19937_64 mt64(rd()); // Get seed from random_device
std::uniform_int_distribution<int> uid(1, 5);
for (int i = 0; i < limit; ++i) {
hist[uid(mt64)] += 1;
}
show_histogram("uniform_int_distribution with mt19937_64", hist);
}
return 0;
}