views:

119

answers:

3

Say I have an array with objects, 1, 2, 3 and 4. How would I pick a random object from this array?

+2  A: 

Generate a random number and use it as the index.

Graham Lee
So simple and yet it works so well!
Joshua
@Joshua if you want a little more detail, you can use `SecRandomCopyBytes()` to get cryptographically-useful random numbers, on the iPhone anyway. On Mac you have direct access to /dev/random.
Graham Lee
@Graham A Random Number should suffice but thanks anyway for the added information.
Joshua
+2  A: 

Perhaps something along the lines of:

NSUInteger randomIndex = (NSUInteger)floor(random()/RAND_MAX * [theArray count]);

Don't forget to initialize the random number generator (srandomdev(), for example).

NOTE: I've updated to use -count instead of dot syntax, per the answer below.

Darryl H. Thomas
That's even better, thanks for including a code snippet!
Joshua
+3  A: 

@Darryl's answer is correct, but could use some minor tweaks:

NSUInteger randomIndex = arc4random() % [theArray count];

Modifications:

  • Using arc4random() over rand() and random() is simpler because it does not require seeding (calling srand() or srandom()).
  • The modulo operator (%) makes the overall statement shorter, while also making it semantically clearer.
  • theArray.count is wrong. It will work, but count is not declared as an @property on NSArray, and should therefore not be invoked via dot syntax. That it works is simply a side-effect of how dot syntax is interpreted by the compiler.
Dave DeLong
Note that RC4/ARC4 doesn't give uniform output.
Graham Lee
Thanks for your suggestions.
Darryl H. Thomas