3

Possible Duplicate:
What's the Best Way to Shuffle an NSMutableArray?
Non repeating random numbers

How to get random indexes of NSMutableArray without repeating? I have NSMutableArray *audioList. I want to play each track in shuffle mode, without repeating. How to do this in the best way?

Community
  • 1
  • 1
Timur Mustafaev
  • 4,869
  • 9
  • 63
  • 109
  • 3
    Check: http://stackoverflow.com/questions/56648/whats-the-best-way-to-shuffle-an-nsmutablearray – jussi Sep 05 '11 at 11:14
  • 2
    @Timur: yes it is. This answer http://stackoverflow.com/questions/56648/whats-the-best-way-to-shuffle-an-nsmutablearray/56656#56656 is aexactly what you want. – JeremyP Sep 05 '11 at 11:22
  • I don't want to reorder my array. I want to get indexes and reorder them in another array. – Timur Mustafaev Sep 05 '11 at 11:25
  • 2
    @Timur: Well copy the array then and shuffle the copy (use `-mutableCopy`). – JeremyP Sep 05 '11 at 11:30

2 Answers2

4

See the code below:

int length = 10; // int length = [yourArray count];
NSMutableArray *indexes = [[NSMutableArray alloc] initWithCapacity:length];
for (int i=0; i<10; i++) [indexes addObject:[NSNumber numberWithInt:i]];
NSMutableArray *shuffle = [[NSMutableArray alloc] initWithCapacity:length];
while ([indexes count])
{
    int index = rand()%[indexes count];
    [shuffle addObject:[indexes objectAtIndex:index]];
    [indexes removeObjectAtIndex:index];
}
[indexes release];
for (int i=0; i<[shuffle count]; i++)
    NSLog(@"%@", [shuffle objectAtIndex:i]);

Now in shuffle you will have indexes of your array without repeating.

Hope, this will help you

Nekto
  • 17,837
  • 1
  • 55
  • 65
2

Nekto's answer is great, but I would change two things:

1) Instead of using rand(), use arc4random() for less predictable results (more details here):

int index = arc4random() % [indexes count];

2) To output contents of "shuffle", use [myArray description] (no need to use a for loop):

NSLog(@"shuffle array: %@", [shuffle description]);
Community
  • 1
  • 1
bdurao
  • 555
  • 3
  • 6
  • To simplify further, calling `NSLog(@"shuffle array: %@", shuffle);` is equivalent to `NSLog(@"shuffle array: %@", [shuffle description]);` since `%@` sends the message `description` to the object. – PengOne Oct 24 '11 at 20:37