Last active
November 3, 2020 21:20
-
-
Save klmr/62863c3d9f5827df23ae2e1415b0cb1b to your computer and use it in GitHub Desktop.
Correctly seed an arbitrary RNG in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <algorithm> | |
#include <array> | |
#include <functional> | |
#include <random> | |
template <typename T = std::mt19937> | |
auto get_random_generator() -> T { | |
auto constexpr seed_bytes = sizeof(typename T::result_type) * T::state_size; | |
auto constexpr seed_len = seed_bytes / sizeof(std::seed_seq::result_type); | |
auto seed = std::array<std::seed_seq::result_type, seed_len>(); | |
auto dev = std::random_device(); | |
std::generate_n(begin(seed), seed_len, std::ref(dev)); | |
auto seed_seq = std::seed_seq(begin(seed), end(seed)); | |
return T{seed_seq}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment