Let's say I have a NSArray with 50-100 objects inside. How can I put the array in a random order?
Asked
Active
Viewed 6,138 times
2
-
Only reason I submitted the question is because I searched extensively and couldn't find a duplicate thread. Thanks for the link! – Don Wilson Aug 05 '10 at 04:14
2 Answers
15
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.

jstm88
- 3,335
- 4
- 38
- 55
-
3
-
This is a version of the Fisher-Yates algorithm. http://en.wikipedia.org/wiki/Fisher–Yates_shuffle – JeremyP Aug 04 '10 at 08:29
-
-3
NSArray *test = [NSArray arrayWithObjects:@"AA",@"BC",@"DE",@"EG",@"FA",@"GQ",@"DA"];<br>
NSSet *testset = [NSSet setWithArray:test];
NSArray *randomorder = [testset allObjects];
NSLog(@"random : %@",randomorder);<br><br>
Apparently there is no indexes for NSSet. Therefore, an NSArray object might be jumbled up when converted to NSSet and back. It's a hack solution, but it works (not sure about this).
-
1
-
@AlexReynolds You already know. In the NSSet remains only unique items. – Guntis Treulands Mar 25 '21 at 06:40
-
In other words, making a set from an array may need to account for duplicate elements. – Alex Reynolds Mar 25 '21 at 07:47