Last active
September 29, 2015 18:21
-
-
Save jcausey-astate/16ec4dbcd388bc2af870 to your computer and use it in GitHub Desktop.
A simple function to generate random integers in a specified range using modern C++ random functions. Inspired by Stephan T. Lavavej's 2013 talk: https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful
This file contains 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
/** | |
* @file easy_rand.h | |
* | |
* Makes it easy to generate good pseudo-random values in a | |
* given numerical range using the new C++11 <random> features, | |
* without the setup overhead. | |
*/ | |
#ifndef EASY_RAND_H | |
#define EASY_RAND_H | |
#include <random> | |
/** | |
* @brief returns a pseudo-random integer in the interval [low, high] | |
* @details Sets up an mt19937 Mersenne Twister random number generator | |
* using a random seed obtained from the best entropy source | |
* available to the <random> library. | |
* Note: Setup time on the first call to this function will cause | |
* the first call to be slightly slower than subsequent | |
* calls. | |
* | |
* @param low lower-bound of interval for random value (included in interval) | |
* @param high upper-bound of interval for random value (included in interval) | |
* | |
* @return pseudo-random integer in the range [low, high] | |
*/ | |
int rand_between(int low, int high){ | |
static std::random_device seeder; // used to seed with system entropy | |
static std::mt19937 generator{seeder()}; // set up (and seed) the PRNG | |
std::uniform_int_distribution<int> distribution{low, high}; // set up distribution for requested range | |
return distribution(generator); // generate and return result | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment