How to randomize an NSArray? [duplicate]

梦想与她 提交于 2019-12-08 01:48:55

问题


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:

  1. Generate a random number between 0 and 49 (assuming 50 elements)
  2. Swap elements 0 and whatever number you generate
  3. Generate a random number between 1 and 49
  4. Swap elements 1 and whatever number you generate
  5. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!