Possible Dupl开发者_JS百科icate:
Non repeating random numbers in Objective-C
How to generate non repeating random numbers?
I saw this on many sites but they give in main.c file code.
When I use the main.c file the code working is fine, but when I try to convert in to my.m file it is not working.
example:
I need to get all the numbers between 0-10 randomly.and the numbers should not repeat again.
Use arc4random() Example:
- (NSData *)randomBytes:(size_t)count
{
NSMutableData *data = [NSMutableData dataWithLength:count];
SecRandomCopyBytes( kSecRandomDefault,
data.length,
data.mutableBytes);
return data;
}
It turns out that getting a random number in a range is not as simple as using mod.
- (u_int32_t)randomInRangeLo:(u_int32_t)loBound toHi:(u_int32_t)hiBound
{
u_int32_t random;
int32_t range = hiBound - loBound + 1;
u_int32_t limit = UINT32_MAX - (UINT32_MAX % range);
do {
random = arc4random();
} while (random > limit);
return loBound + (random % range);
}
CocoaFu provides excellent random numbers. What you're asking for is a shuffle. The easiest is a Fischer-Yates shuffle. There are several good versions provided in the Wikipedia article. You can also read about the modulo bias that CocoaFu's algorithm avoids.
But there is absolutely no reason a C implementation will not work precisely the same in Objective-C. If you've had problems moving from a .c
file to a .m
file, you should post your errors.
精彩评论