سؤال

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.

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top