Possible Duplicate:
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With