Let's say I have a NSArray with 50-100 objects inside. How can I sort the array into a random order?
+4
A:
There are a lot of ways to do it, but most will involve simply generating random numbers. Perhaps you could use this technique using an NSMutableArray:
- Generate a random number between 0 and 49 (assuming 50 elements)
- Swap elements 0 and whatever number you generate
- Generate a random number between 1 and 49
- Swap elements 1 and whatever number you generate
- Etc.
That would probably be the most efficient way.
Sample code (not tested):
srandom(time(NULL));
for (NSInteger x = 0; x < [array count]; x++) {
NSInteger randInt = (random() % ([array count] - x)) + x;
[array exchangeObjectAtIndex:x withObjectAtIndex:randInt];
}
Also, you could use two NSMutableArray objects, and simply loop through while the first has objects, choose one randomly, and add it to the end of the other one. The in place method is probably faster though.
jfm429
2010-08-04 03:16:33
using arc4random() is much better!
nonamelive
2010-08-04 07:50:50
This is a version of the Fisher-Yates algorithm. http://en.wikipedia.org/wiki/Fisher–Yates_shuffle
JeremyP
2010-08-04 08:29:52