Skip to content

Instantly share code, notes, and snippets.

@opatut
Created June 3, 2011 16:27
Show Gist options
  • Save opatut/1006641 to your computer and use it in GitHub Desktop.
Save opatut/1006641 to your computer and use it in GitHub Desktop.
c++0x random generator
#include <iostream>
#include <ctime>
#include <random>
class Random {
public:
static void Initialize() {
Generator.seed(time(0));
}
static int Get(int min, int max) {
return std::uniform_int_distribution<int>(min, max)(Generator);
}
static float Get(float min, float max) {
return std::uniform_real_distribution<float>(min, max)(Generator);
}
private:
static std::mt19937 Generator;
};
std::mt19937 Random::Generator;
int main()
{
Random::Initialize();
for(int i = 0; i < 10; ++i)
std::cout << Random::Get(0, 100) << std::endl;
for(int i = 0; i < 10; ++i)
std::cout << Random::Get(0.f, 100.f) << std::endl;
return 0;
}
#include <iostream>
#include <ctime>
#include <random>
template <typename T>
class RandomGenerator
{
public:
RandomGenerator() {
mGenerator.seed(time(0));
}
virtual T operator()(T min, T max) = 0;
protected:
std::mt19937 mGenerator;
};
class RandomInt : public RandomGenerator<int> {
public:
int operator()(int min, int max) {
return std::uniform_int_distribution<int>(min, max)(mGenerator);
}
};
class RandomFloat : public RandomGenerator<float> {
public:
float operator()(float min, float max) {
return std::uniform_real_distribution<float>(min, max)(mGenerator);
}
};
int main()
{
RandomInt ir;
for(int i = 0; i < 10; ++i)
std::cout << ir(0, 100) << std::endl;
RandomFloat fr;
for(int i = 0; i < 10; ++i)
std::cout << fr(0, 100) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment