문제

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