1

Have an NSMutableArray, and when my users press a button, I'd like all items in the array to randomly change position, !! except for the first !!.

Right now I have

-(void)shufflemyList{

NSLog(@"Un Shuffled array : %@",myList);
NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
while ([myList count] > 0)
{
    int index = arc4random() % [myList count];
    id objectToMove = [myList objectAtIndex:index];
    [array addObject:objectToMove];
    [myList removeObjectAtIndex:index]; }

// test
NSLog(@"Shuffled array : %@",array);
myList=array;  }

This works to completely shuffle the list. Is there a way to shuffle the whole list, excepting the first item?

  • This topic could be interesting for you http://stackoverflow.com/questions/23393589/is-this-a-sufficient-way-to-shuffle-a-deck-of-cards/23393717#23393717. – Avt May 03 '14 at 22:14

1 Answers1

0

Just add 2 lines

-(void)shufflemyList{

NSLog(@"Un Shuffled array : %@",myList);
NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
// new code ---
[array addObject:myList[0]];
[myList removeObjectAtIndex:0];
// ---
while ([myList count] > 0)
{
    int index = arc4random() % [myList count];
    id objectToMove = [myList objectAtIndex:index];
    [array addObject:objectToMove];
    [myList removeObjectAtIndex:index]; }

// test
NSLog(@"Shuffled array : %@",array);
myList=array;  }

Also it is better to use 'arc4random_uniform(n)' instead of 'arc4random() % n'. From docs:

arc4random_uniform() will return a uniformly distributed random number less than upper_bound. arc4random_uniform() is recommended over constructions like ``arc4random() % upper_bound'' as it avoids "modulo bias" when the upper bound is not a power of two.

Avt
  • 16,927
  • 4
  • 52
  • 72