Cocoa, Python and Java Programming Adventures

Array Shufflin’

I recently added two simple methods to NSArray and NSMutableArray through a Category, the Objective-C way of extending an existing class.

You can find the code on Github in my Cocoa Utils repository.

With these additions you can easily randomize the contents of an existing NSMutableArray:

NSMutableArray* array = [NSMutableArray arrayWithObjects:
   @"1", @"2", @"3", @"4", @"5", @"6", nil];
[array shuffle];

Or create a new NSArray by shuffling an array you already have:

NSArray* array = [NSArray arrayWithObjects: @"1", @"2", @"3", @"4", @"5", @"6", nil];
NSArray* shuffled = [NSArray shuffledArrayWithArray: array];

The shuffling algorithm that I use is called Fisher-Yates. It is very basic but seems to do the trick.

1 response to “Array Shufflin’”

  1. #1. Snippet: Array shuffling at Under The Bridge on November 6th, 2009 at 02:08

    [...] to quickly shuffle an array, for a deck of cards or whatever? Here’s categories for NSArray and NSMutableArray to do that [...]

Leave a Reply