Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 803
sietschie Avatar asked Jul 05 '26 04:07

sietschie


2 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:

enter image description here Source

like image 165
Richard J. Ross III Avatar answered Jul 06 '26 22:07

Richard J. Ross III


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.

like image 35
futureelite7 Avatar answered Jul 06 '26 21:07

futureelite7



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!