Programming/C++

[A tour of C++] Ch 14. Numerics

dododoo 2020. 1. 15. 21:45

14.5 Random Numbers

난수 생성기는 크게 두 부분으로 구성된다.

- engine: 난수 또는 psuedo-난수의 시퀀스를 생성함

- distribution: 이러한 값을 어떤 범위 안의 수학적 분포로 매핑함

#include <iostream>
#include <vector>
#include <random>
#include <limits>
using namespace std;

class Rand_int {
public:
    Rand_int(int low = numeric_limits<int>::min(), int high = numeric_limits<int>::max()) 
        : rd{}, rnd{rd()}, dist{low, high} {}
    int operator()() { return dist(rnd); }
private:
    random_device rd;
    mt19937 rnd;
    uniform_int_distribution<> dist;
};

int main()
{
/*  range of int
    Rand_int rnd;
    for (int i = 0; i < 10; ++i)
        cout << rnd() << '\n';
*/

    Rand_int dice {1, 6};
    vector<int> hist(6 + 1);
    for (int i = 0; i < 200; ++i)
        ++hist[dice()];
    
    for (int i = 1; i <= 6; ++i) {
        cout << i << ": ";
        for (int j = 0; j < hist[i]; ++j)
            cout << "*";
        cout << '\n';
    }

    return 0;
}