Multiple random number generators in Objective C

In my current project I need multiple random number generators because I need to be able to repeat their sequences independently from each other. So far I did not find any way to achieve this with the standard objective-c random number generators, because they only have one global state.

I think having an random number generator class would solve my problem. I could create several instances which I could reset individually.

Is something like this already available? I was not able to find any random number generator implementation in objective c. I would like to avoid implementing it myself because I have no experience with random numbers and I think it is something that's hard to get right.

Answers


I have a random class, based on the Mersenne Twister algorithm, which you can get from my dropbox here.

It's rather old, and isn't compiled for ARC, but that doesn't make it any less good :)

Example code:

MTRandom *randWithSeed = [[MTRandom alloc] initWithSeed:12345];
double d = [rand nextDouble];
int i = [rand nextInt];

MTRandom *timeBasedRand = [MTRandom new]; // seeds with current time
double d2 = [timeBasedRand nextDouble];
int i2 = [timeBasedRand nextInt];

EDIT: If you want to be really cool, you can use this:

Source


Have you tried

srandom(seed);

and then calling

random();

? If the seeds are the same then you should get the same sequence of random numbers.


Need Your Help

How to fetch the values from MySQL with switch case in PHP

php mysql switch-statement

I'm working with PHP and MySQL on a student registration project.