2

Let's say I have a NSArray with 50-100 objects inside. How can I put the array in a random order?

Casebash
  • 114,675
  • 90
  • 247
  • 350
Don Wilson
  • 558
  • 2
  • 8
  • 21
  • 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 Answers2

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:

  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.

jstm88
  • 3,335
  • 4
  • 38
  • 55
-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).

beakr
  • 5,709
  • 11
  • 42
  • 66
wahkiz
  • 616
  • 5
  • 13