Short question: How to generate random numbers without disturbing the random sequence already created? OR, How to restart a random number sequence at a position not known at compile time?
Long question: I have a program which uses a random number sequence, and for which the same random seed is always used during testing (1 in this case). However, as classes get changed, they may call that random sequence, creating an issue where the random numbers in the main are no longer the same due to the fact that the sequence has been advanced by those changed classes.
Here is a short snippet which shows the underlying phenomenon. Lets assume that foo has either been added, or changed in such a way that it alters the random number sequence.
#include<iostream>
void foo(void);
int main() {
srand(1);
std::cout << rand() << '\t' << rand() << std::endl;
srand(1);
foo();
std::cout << rand() << '\t' << rand() << std::endl;
return 0;
}
void foo(void) {
// Some other function/class member that uses rand( )
rand();
}
Which is, at least on my machine, kicking out the following values:
18467 41
6334 18467
Option one, which is nearly as impractical to implement as it is obvious, is to simply go count/calculate the number of times rand( ) gets called in the main and all of its called functions/classes and then reseed and use a dummy loop to advance the sequence to the correct position. Unfortunately, this is not practical as mentioned, so a different method is required.
The first potential solution for which I attempted to find code, was to create a local rand( ) sequence specific to that class or function and pull numbers from that, leaving the original sequence untouched.
The second potential solution for which I attempted to find code, was to restart that sequence from some arbitrary position, but I know neither how to get that position nor how to restart it at that position.
So then, without specifically knowing how many times rand( ) has been called, how can I save the position in the sequence and then restart that sequence after reseeding and/or other calls to rand( ) may have taken place? OR, alternatively, generate random numbers in those classes/functions without disturbing the already in progress rand( ) sequence?
Aucun commentaire:
Enregistrer un commentaire