Skip to content

Instantly share code, notes, and snippets.

@gintenlabo
Last active August 29, 2015 14:04
Show Gist options
  • Save gintenlabo/705a016024dee29c5cb3 to your computer and use it in GitHub Desktop.
Save gintenlabo/705a016024dee29c5cb3 to your computer and use it in GitHub Desktop.
Random Number Generation for C++11, thanks to http://cpplover.blogspot.jp/2009/11/c0xrandom.html
#include <random>
#include <iterator>
template<class RandomGen>
auto make_random_values(RandomGen&& gen, std::size_t n)
-> std::vector<typename RandomGen::result_type> {
std::vector<typename RandomGen::result_type> result;
result.reserve(n);
for (std::size_t i = 0; i < n; ++i) {
result.push_back(gen());
}
return result;
}
template<class RandomEngine, class Seeds>
RandomEngine make_random_engine_from_seeds(Seeds const& seeds) {
using std::begin;
using std::end;
std::seed_seq sseq(begin(seeds), end(seeds));
return RandomEngine(sseq);
}
std::mt19937& get_random_generator() {
thread_local std::mt19937 gen =
make_random_engine_from_seeds<std::mt19937>(
make_random_values(std::random_device(), 16));
return gen;
}
#include <iostream>
int main() {
auto& gen = get_random_generator();
std::uniform_int_distribution<> dist(1, 6);
for (int i = 0; i < 10; ++i) {
std::cout << dist(gen) << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment