You can use the following piece of code to randomize/shuffle the objects inside a NSMutableArray.
/* anArray is a NSMutableArray with some objects */ srandom(time(NULL)); NSUInteger count = [anArray count]; for (NSUInteger i = 0; i < count; ++i) { int nElements = count - i; int n = (random() % nElements) + i; [anArray exchangeObjectAtIndex:i withObjectAtIndex:n]; }
Update @ 2012-07-18: Suggestion from kimbebot
/* anArray is a NSMutableArray with some objects */ NSUInteger count = [anArray count]; for (NSUInteger i = 0; i < count; ++i) { int nElements = count - i; int n = (arc4random() % nElements) + i; [anArray exchangeObjectAtIndex:i withObjectAtIndex:n]; }
Done =)
Reference: StackOverflow – What’s the Best Way to Shuffle an NSMutableArray?
Very useful piece of code. You saved my day. Thanks a lot.
LikeLike
Glad to know that it helps you~~ =)
LikeLike
Thank u very very much it helped me a lot
LikeLike
thanks for your comment and i am glad to know that the post could help =D
LikeLike
I applied the same but i get the error–
*** Terminating app due to uncaught exception ‘NSRangeException’, reason: ‘*** -[NSMutableArray objectAtIndex:]: index 4294967295 beyond bounds [0 .. 26]’
LikeLike
how do u create the mutable array? a nil is needed for the last item.
For examplp:
LikeLike
Thanks for this brute force approach. I just paste this into my code, spaghetti style 🙂
I tried to make it nicer, like in http://stackoverflow.com/questions/56648/whats-the-best-way-to-shuffle-an-nsmutablearray, but I can’t put 2 hours work to find out how to extend a class properly. ;-P
LikeLike
Good to know the it could help. =)
LikeLike
Thanks for this tutorial and I find it useful, although this code srandom(time(NULL)); is not necessary so we can remove it. And we should also use arc4random() instead of random(). Anyway, thanks for this!
LikeLike
thanks for your suggestion and i have updated this post. =)
LikeLike