Created
June 3, 2011 16:27
-
-
Save opatut/1006641 to your computer and use it in GitHub Desktop.
c++0x random generator
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 <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; | |
} |
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 <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