I have an unsigned int storing a random number. I need to use this number to generate a series of “random like” numbers and have it generate those exact same numbers if this original random number turns up again.
i.e.
Random number: 123456789
First “random like number”: 3
Second “random like number”: 7
Third “random like number”: 1
Fourth “random like number”: 9
and so on.
Next time that random number comes around, the exact same numbers need to be generated from it.
The non random numbers can be duplicated and/or wrap around (to start again if whatever algorithm is used runs out of numbers, it can start again from the beginning). Just as long as each time, those same numbers are generated.
I realise this is exactly what rand() does (seeding with the random number), however I cannot use rand. So perhaps a more concise question would be how do I replicate a “mini” rand function (it doesn’t have to be anything complicated, just so long as the numbers coming out look somewhat randomised).
Also I cannot use boost (unfortunately).
Any pointers/tips?
I don’t know exactly why you cannot use
randitself but, if not, then you could just roll your own. Use your integer to seed a number then use the standardXn+1 = a * Xn + c mod m.The Wikipedia page for linear congruential method has some sample values for
a,candm.Now LCM isn’t the greatest random number generator in the world but, if you just want numbers that “look somewhat randomised”, it should be sufficient.
As an example of an LCM algorithm, the following function, based on the
Microsoft Visual/Quick C/C++entry from that linked page above:has a cycle time of the full range of 32-bit numbers but only returns certain bits of the seed each time, which reduces the appearance of identical sequences.
If you want a C++ class to do this so that all random number generators are independent of each other (as suggested by TomZ), you can use something like: