0

Possible Duplicate:
canonical way to randomize an NSArray in Objective-C

Suppose I have an array as follows.

shuffleArray = [[NSMutableArray alloc] initWithObjects:@"A",@"B",@"C",@"D",@"E", nil];

and I want to change the position of elements of the array randomly as follows:

shuffleArray = [[NSMutableArray alloc] initWithObjects:@"C",@"A",@"B",@"E",@"D", nil];

then how can I do this?

Cœur
  • 37,241
  • 25
  • 195
  • 267
K.P.
  • 324
  • 4
  • 13
  • You could follow this link: http://stackoverflow.com/questions/4349669/nsmutablearray-move-object-from-index-to-index – SimplyKiwi May 12 '12 at 06:28
  • this http://stackoverflow.com/questions/5659718/shuffling-an-array-in-objective-c can solve your issue – V.V May 12 '12 at 06:29

2 Answers2

0
-(NSArray *)shuffleme
{

 NSMutableArray *array = [NSMutableArray arrayWithCapacity:[self count]];

 NSMutableArray *array1 = [self mutableCopy];
 while ([array1 count] > 0)
 {
  int temp = arc4random() % [array1 count];
  id objectToMove = [array1 objectAtIndex:temp];
  [array addObject:objectToMove];
  [array1 removeObjectAtIndex:temp];
 }

   [array1 release];
   return array;
}

Hope, this will help you..

Nitin
  • 7,455
  • 2
  • 32
  • 51
0
-(void)changeObjectAtIndex:(int)index1 index2:(int)index2 array:(NSMutableArray *)array
{
     id objectAtIndex1=[array objectAtIndex:index1];
     [array insertObject:[array objectAtIndex:index2] atIndex:index1];
     [array insertObject:id atIndex:index2];
}

This is For swapping objects at two indexes and you can make this function recursive if you know exactly where you want particular objects.But if you want it randomly then you can adopt Nit's Method.

Randomly can also be done by:-

id newObject= [[[yourArray objectAtIndex:index] retain] autorelease];
[yourArray  removeObjectAtIndex:index];
[yourArray  insertObject:object atIndex:yourIndex];

keep in mind to retain the object.

Abhishek Singh
  • 6,068
  • 1
  • 23
  • 25