问题
Let's say I have a NSArray with 50-100 objects inside. How can I put the array in a random order?
回答1:
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.
回答2:
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).
来源:https://stackoverflow.com/questions/3402312/how-to-randomize-an-nsarray