Question

Besides being a rubbish programmer, my jargon is not up to scratch. I am going to try my best to explain myself. I have implemented a Merssene twister random number generator using randomlib. Admittedly I am not too familiar on how Visual 8 C++'s random number generator works, but I find I can seed it once srand(time(NULL)) in main() and I can safely use rand() in my other classes. The Merssene twister that I have one needs to create an object, and then seed that object.

#include <RandomLib/Random.hpp>
RandomLib::Random r;        // create random number object
r.Reseed();                 // seed with a "unique" seed
float d = r.FloatN();   // a random in [0,1] rounded to the nearest double

If I want to generate a random number in a class how do I do this without having to define an object each time. I am just worried that if I use the computer clock I will use the same seed each run (only changes every second).

Am I explaining myself right?

Thanks in advance

Was it helpful?

Solution

The Random object is essentially state information that you need to preserve. You can use all the normal techniques: You could have it as a global variable or pass it around as a parameter. If a particular class needs random numbers you can keep a Random object as a class member to provide randomness for that class.


The C++ <random> library is similar in that it requires the construction of an object as the source of randomness/RNG state. This is a good design because it allows the program to control access to the state and, for example, guarantee good behavior with multiple threads. The C++ <random> library even includes mersenne twister algorithm.

Here's an example showing saving a RNG state as a class member (using std::mt19937 instead of Random)

#include <random> // for mt19937
#include <algorithm> // for std::shuffle
#include <vector>

struct Deck {
    std::vector<Cards> m_cards;
    std::mt19937 eng; // save RNG state as class member so we don't have to keep creating one

    void shuffle() {
        std::shuffle(std::begin(m_cards), std::end(m_cards), eng);
    }
};

int main() {
    Deck d;
    d.shuffle();
    d.shuffle(); // this reuses the RNG state as it was at the end of the first shuffle, no reseeding
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top