3

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Thukaram
  • 1,085
  • 2
  • 13
  • 33
  • There is no such thing. Any computer generated random number will be a repeating sequence. – Paul Tomblin Sep 20 '11 at 12:01
  • 1
    There are what are called "cryptographically secure" random numbers. They gain entropy continually from many events on the computer. For all intents they are random. The access function is arc4random(). – zaph Sep 20 '11 at 12:04

2 Answers2

2

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);
}
zaph
  • 111,848
  • 21
  • 189
  • 228
  • Well there is a way: if you number has to be between 10 and 50: `random = (arc4random()%40) + 10;` – rckoenes Sep 20 '11 at 12:08
  • 3
    Yes,that will provide a number in a range but it is biased by the way it is restricted (mod). You will see this done a lot but it is wrong. Getting cryptography correct is hard. – zaph Sep 20 '11 at 12:12
  • but i want every single number between that range to be displayed – Thukaram Sep 20 '11 at 12:22
  • 1
    Every number in the range will be displayed without bias, that is the point. Using mod (%) will create results that have a bias (toward lower numbers), the bias may be small and the bias may not be important in most usages. Make a choice but understand what you are choosing. – zaph Sep 20 '11 at 12:38
1

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.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610