Filed under: Cocoa

Sorting a NSMutableArray Randomly - Shuffle

Earlier today, I had a situation where I needed the contents of a NSMutableArrray in a random order.

There are many way in which this could be achieved, however I decided to build a Category onto NSMutableArray itself to aid in the reuse of the code, and to provide some features out of the box because the project I was actually developing was a static library for use in other project.
I am posting the code here in case anyone else finds it useful, and so I know where it is, should I ever need it again in the future.
interface:
//  NSMutableArray_Shuffling.h
//  Created by Mick Walker on 11/04/2011.
//
 
#if TARGET_OS_IPHONE
#import "UIKit/UIKit.h"
#else
#include <Cocoa/Cocoa.h>
#endif
 
 
@interface NSMutableArray (Shuffling)
- (void) shuffle;
@end

implementation:
//  NSMutableArray_Shuffling.m
//  Created by Mick Walker on 11/04/2011.
//
 
#import "NSMutableArray_Shuffling.h"
 
 
@implementation NSMutableArray (Shuffling)
 
-(void) shuffle {
    NSUInteger count = [self count];
    for(NSUInteger i = 0; i < count; i++){
        int nElements = count -1;
        int n = (arc4random() %nElements) + 1;
        [self exchangeObjectAtIndex:i withObjectAtIndex:n];
    }
}
@end

Using the code is simple, simply import the header file:
#import "NSMutableArray_Shuffling.h"

And then on an initialised NSMutableArray object call:
[someArray shuffle];
I hope that this post helps someone.