I generate a few thousand object in my program based on the C++ rand() function. Keeping them in the memory would be exhaustive. Is there a way to copy the CURRENT seed of rand() at any given time? This would give me the opportunity to store ONLY the current seeds and not full objects. (thus I could regenerate those objects, by regenerating the exact same sub-sequences of random numbers)
An exhaustive solution is storing the full sequence of random numbers given by rand() - doesn't worth it. Another would be solution is to implement my own class for randomized numbers.
Google gave me no positive clues. There are hundreds of articles teaching the basics of rand and srand, and I couldn't find the specific ones.
Does anyone know other random number generators with implemented seed-stealer?
Thank you for your fast answers! There are more possible answers/solutions to this question, so I made a list of your answers here.
SOLUTIONS:
The short answer is: there is no standard way to get the seed
The closest possible workaround is to save the INITIAL seed in the beginning, and count how many times you call the rand() function. I marked this as solution because it works on the current std::rand() function of every compiler (and this was the main question about). I've benchmarked my 2.0 GHz CPU, and found that I can call&count rand() 1,000,000,000 times in 35 seconds. This might sound good, but I have 80,000 calls to generate one object. This restricts the number of generations to 50,000 because the size of unsigned long. Anyway, here is my code:
class rand2 { unsigned long n; public: rand2 () : n(0) {} unsigned long rnd() { n++; return rand(); } // get number of rand() calls inside this object unsigned long getno () { return n; } // fast forward to a saved position called rec void fast_forward (unsigned long rec) { while (n < rec) rnd(); } };
Another way is to implement your own Pseudo-random number generator, like the one Matteo Italia suggested. This is the fastest, and possibly the BEST solution. You're not restricted to 4,294,967,295 rand() calls, and don't need to use other libraries either. It's worth mentioning that different compilers have different generators. I've compared Matteo's LCG with rand() in Mingw/GCC 3.4.2 and G++ 4.3.2. All 3 of them were different (with seed = 0).
Use generators from C++11 or other libraries as Cubbi, Jerry Coffin and Mike Seymour suggested. This is the best idea, if you're already working with them. Link for C++11 generators: http://en.cppreference.com/w/cpp/numeric/random (there are some algorithm descriptions here too)
unsigned long
counter to count the overflows. This would effectively double the bit size of your counter and can, of course, further extended. – Ornithischian