Skip to content

Instantly share code, notes, and snippets.

@antoni
Created February 28, 2016 21:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antoni/8e2d9a846c2140c9a0e2 to your computer and use it in GitHub Desktop.
Save antoni/8e2d9a846c2140c9a0e2 to your computer and use it in GitHub Desktop.
Generate random number in range (C++)
#include <random>
int main(int argc, char *argv[]) {
#ifdef APPROACH1 // C++11
std::random_device rd; // used once to initialise (seed) engine
// random-number engine (Mersenne-Twister in this case)
std::mt19937 rng(rd());
std::uniform_int_distribution<int> uni(min, max); // guaranteed unbiased
auto random_integer = uni(rng);
#endif
#ifdef APPROACH2
int min = 0, max = 128;
int random_value = min + (rand() % (int)(max - min + 1))
#endif
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment