Use rand_r()
. With that function, the seed is not global and implicit. You pass the seed to use explicitly and the function updates it as it computes the next random number. That way, each class's stream of random numbers is independent of the others'.
Each object or each class (depending on your design needs) would store a seed value in an unsigned int
variable. It would initialize it; for objects, in the init method; for classes, in +initialize
. You could use the time or perhaps /dev/random
for the initial value. If you initialize several such objects or classes in close succession, then using the time is a bad idea, since they may all happen at the "same" time (within the resolution of the clock you use).
After that, each time you want a random number, you call rand_r(&yourSeedVariable)
. That will return a pseudo-random value computed only from the passed-in seed, not using any implicit or global state. It uses the same algorithm as rand()
. It also updates the seed variable such that the next call will produce the next random number in that sequence.
Any other object or class using this same technique would have an independent random sequence. Their calls to rand_r()
would not affect this object's or class's and this object's or class's calls will not affect them. Same for any callers of rand()
.
To clarify a bit further. You said in one of the edits to your question:
The reason I want to "jump" to the nth term, is because I use rand in
different classes with different seeds, and I keep jumping back and
forth between each class. I want the sequence in each class to
continue where it left off, instead of starting from the first number
each time.
I am addressing that need with my suggestion. My suggestion does not address your question as phrased originally. It does not let you get the *n*th number in a pseudo-random sequence. It instead lets you use separate sequences in separate parts of your code such that they don't interfere with each other.