Say I have an array with objects, 1, 2, 3 and 4. How would I pick a random object from this array?
So simple and yet it works so well!
Joshua
2010-07-23 14:20:09
@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
2010-07-23 14:31:32
@Graham A Random Number should suffice but thanks anyway for the added information.
Joshua
2010-07-23 14:37:50
+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
2010-07-23 14:19:52
+3
A:
@Darryl's answer is correct, but could use some minor tweaks:
NSUInteger randomIndex = arc4random() % [theArray count];
Modifications:
- Using
arc4random()
overrand()
andrandom()
is simpler because it does not require seeding (callingsrand()
orsrandom()
). - The modulo operator (
%
) makes the overall statement shorter, while also making it semantically clearer. theArray.count
is wrong. It will work, butcount
is not declared as an@property
onNSArray
, 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
2010-07-23 14:39:38