Sunday, 24 November 2013

How to shuffle an NSMutableArray in an easy way

There are several methods to sort an NSMutableArray. Here we will give you a very simple method to shuffle your NSMutableArray. This method uses the default exchangeObjectAtIndex method to shuffle the array.

Lets initialise a mutable array and add some elements to it as below:

 // Initialising the NSMutableArray
   NSMutableArray *myArray = [[NSMutableArray alloc]init];

 // Add some objects to it (say 15, here) 
   for (int i=1; i<=15; i++) {
     [myArray addObject:[NSString stringWithFormat:@"%d",i]];
   }

Now you have an array with 15 objects/elements in it. Now for sorting the above array, you just need to use the following code:

 // Code for shuffling
  for (int i = 0; i < [myArray count]; ++i) {
    [myArray exchangeObjectAtIndex:i withObjectAtIndex:((random() % ([myArray count]-i)) + i)];
  }


No comments:

Post a Comment