Is there a canonical way to randomize an array in Objective C?
相关问题
- CALayer - backgroundColor flipped?
- Core Data lightweight migration crashes after App
- Core Data lightweight migration crashes after App
- How can I implement password recovery in an iPhone
- back button text does not change
相关文章
- 现在使用swift开发ios应用好还是swift?
- Could I create “Call” button in HTML 5 IPhone appl
- TCC __TCCAccessRequest_block_invoke
- xcode 4 garbage collection removed?
- Unable to process app at this time due to a genera
- why 48 bit seed in util Random class?
- How can I add media attachments to my push notific
- How do you detect key up / key down events from a
NSArray randomization as Objective-C category method:
As seen: NSArray Randomization & Psychedelia
My utility library defines this category on NSMutableArray to do it:
Make sure you seed the random number generator (with e.g.
srandom(time(NULL))
) sometime before you call it; otherwise the output won't be very random.There isn't a canonical way without making a category on
NSArray
(i.e. have an instance method likearrayWithRandomizedIndices
) orNSMutableArray
(i.e. have a method likerandomizeIndices
).Here's an example from my library, part of a category on
NSMutableArray
. It will randomly reorder the array, rather than shuffle a few entries.Call
srand(time(0));
or some such before calling this method or early in the method.Here it is!
Make sure to seed the random() function with either srandomdev() or srandom().
My solution is a category method that returns a copy of the array (autoreleased) with elements randomised (using arc4random).