Question

is it possible to get the internal state of an rng-engine? I think about implementing a game and I want to store the internal state of the rng-engine inside the save file so that saving and reloading does not alter the game.

The only possibility that I can think of currently is saving the seed and the number of random numbers taken from that engine but I hope that there is something more elegant.

Any Ideas? Regards Tobias

Was it helpful?

Solution

From cppreference:

Engines and distributions are designed to be used together to produce random values. All of the engines may be specifically seeded, serialized, and deserialized for use with repeatable simulators.

And you'll notice that all the engines have operator<< and operator>> defined. So you should be able to save and load them from a file with these.

Proof of concept:

#include <fstream>
#include <iostream>
#include <random>

int main(int argc, char* argv[])
{
    std::ofstream ofile("out.dat", std::ios::binary);

    std::random_device randDev;
    std::default_random_engine defEngine(randDev());
    std::uniform_int_distribution<int> dist(0, 9);
    auto printSomeNumbers = [&](std::default_random_engine& engine) { for(int i=0; i < 10; i++) { std::cout << dist(engine) << " "; } std::cout << std::endl; };

    std::cout << "Start sequence: " << std::endl;
    printSomeNumbers(defEngine);

    ofile << defEngine;
    ofile.close();

    std::default_random_engine fileEngine;

    std::ifstream ifile("out.dat", std::ios::binary);
    ifile >> fileEngine;

    std::cout << "Orig engine: "; printSomeNumbers(defEngine);
    std::cout << "File engine: "; printSomeNumbers(fileEngine);

    std::cin.get();
    return 0;
}

As can be seen on Coliru, the output is:

Start sequence:

6 5 8 2 9 6 5 2 6 3

Orig engine: 0 5 8 5 2 2 0 7 2 0

File engine: 0 5 8 5 2 2 0 7 2 0

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top