I have been using C++11's new uniform_int_distribution to generate a pseudo-random number, and I was wondering, assuming I only generated 1 number, would it be possible to find the seed that was used to generate that number? Here is my code, nothing fancy.
Here the seed is clearly one, but can I find out that it was one if I hadn't known ahead of time with only the generated value? (which is 289138675122)
In most cases you would just save the value used in your own variable somewhere.
I don't really use the C++11 random library but it seems they overload the input and output functions for serialization, the first value being the seed. This is just my own quick research so no guarantees on anything here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <sstream>
#include <random>
#include <string>
int main()
{
std::mt19937 mt(1);
std::uniform_int_distribution<longlong> udist(0, 500246412960);
std::stringstream input;
input << mt; // Get first word
std::string s;
input >> s;
std::cout<< "Seed for engine is "<< s << std::endl; // 1
}
That's actually useful to know, but sadly I am needing to do this (possibly) in another instance of the program, or even an entirely different program.
Yes, I would be writing both. I am assuming there is no way to find it without actually storing it prior?
EDIT:
Would it make the process of finding the seed easier or more difficult if more numbers were generated? Assuming that they all used the same seed.
EDIT 2:
The exact seed is not necessary, for example, I imagine it is possible more than one seed will produce any given value, so long as I can find anyone of the seeds that do.
> I am needing to do this (possibly) in another instance of the program, or even an entirely different program.
We can rely on consistent, reproducible behaviour across implementations for standard random number engines.
However, there is no such guarantee for standard random number distributions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include <random>
int main()
{
std::mt19937 engine{123456} ;
engine.discard(100) ;
std::cout << engine() << ' ' ; // same value 428366112 everywhere
std::seed_seq seed_seq{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } ;
std::mt19937 engine2 {seed_seq} ;
engine.discard(1000) ;
std::cout << engine2() << ' ' ; // same value 118231844 everywhere
std::uniform_int_distribution<int> distribution( 0, 999999 ) ;
std::cout << distribution(engine2) << '\n' ; // different values on different implementations
}
On stream output, the first value(s) would be the seed(s) only if a seed sequence was not used for initialisation (and the output was performed immediately after engine initialisation).