<p>If you have an <code>NSMutableArray</code>, how do you shuffle the elements randomly?</p>

<p>(I have my own answer for this, which is posted below, but I'm new to Cocoa and I'm interested to know if there is a better way.)</p>

<hr>

<p>Update: As noted by @Mukesh, as of iOS 10+ and macOS 10.12+, there is an <code>-[NSMutableArray shuffledArray]</code> method that can be used to shuffle. See <a href="https://developer.apple.com/documentation/foundation/nsarray/1640855-shuffledarray?language=objc" rel="noreferrer">https://developer.apple.com/documentation/foundation/nsarray/1640855-shuffledarray?language=objc</a> for details. (But note that this creates a new array, rather than shuffling the elements in place.)</p>

[{'answer_id': 56656, 'author': 'Kristopher Johnson', 'author_id': 1175, 'author_profile': 'https://Stackoverflow.com/users/1175', 'pm_score': 8, 'selected': False, 'text': '<p>I solved this by adding a category to NSMutableArray.</p>\n\n<p><strong>Edit:</strong> Removed unnecessary method thanks to answer by Ladd.</p>\n\n<p><strong>Edit:</strong> Changed <code>(arc4random() % nElements)</code> to <code>arc4random_uniform(nElements)</code> thanks to answer by Gregory Goltsov and comments by miho and blahdiblah</p>\n\n<p><strong>Edit:</strong> Loop improvement, thanks to comment by Ron</p>\n\n<p><strong>Edit:</strong> Added check that array is not empty, thanks to comment by Mahesh Agrawal</p>\n\n<pre><code>//  NSMutableArray_Shuffling.h\n\n#if TARGET_OS_IPHONE\n#import &lt;UIKit/UIKit.h&gt;\n#else\n#include &lt;Cocoa/Cocoa.h&gt;\n#endif\n\n// This category enhances NSMutableArray by providing\n// methods to randomly shuffle the elements.\n@interface NSMutableArray (Shuffling)\n- (void)shuffle;\n@end\n\n\n//  NSMutableArray_Shuffling.m\n\n#import "NSMutableArray_Shuffling.h"\n\n@implementation NSMutableArray (Shuffling)\n\n- (void)shuffle\n{\n    NSUInteger count = [self count];\n    if (count &lt;= 1) return;\n    for (NSUInteger i = 0; i &lt; count - 1; ++i) {\n        NSInteger remainingCount = count - i;\n        NSInteger exchangeIndex = i + arc4random_uniform((u_int32_t )remainingCount);\n        [self exchangeObjectAtIndex:i withObjectAtIndex:exchangeIndex];\n    }\n}\n\n@end\n</code></pre>\n'}, {'answer_id': 57643, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 7, 'selected': True, 'text': '<p>You don\'t need the swapObjectAtIndex method. <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableArray/exchangeObjectAtIndex:withObjectAtIndex:" rel="noreferrer">exchangeObjectAtIndex:withObjectAtIndex:</a> already exists.</p>\n'}, {'answer_id': 1299049, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>This is the simplest and fastest way to shuffle NSArrays or NSMutableArrays \n(object puzzles is a NSMutableArray, it contains puzzle objects. I\'ve added to\npuzzle object variable index which indicates initial position in array)</p>\n\n<pre><code>int randomSort(id obj1, id obj2, void *context ) {\n        // returns random number -1 0 1\n    return (random()%3 - 1);    \n}\n\n- (void)shuffle {\n        // call custom sort function\n    [puzzles sortUsingFunction:randomSort context:nil];\n\n    // show in log how is our array sorted\n        int i = 0;\n    for (Puzzle * puzzle in puzzles) {\n        NSLog(@" #%d has index %d", i, puzzle.index);\n        i++;\n    }\n}\n</code></pre>\n\n<p>log output:</p>\n\n<pre><code> #0 has index #6\n #1 has index #3\n #2 has index #9\n #3 has index #15\n #4 has index #8\n #5 has index #0\n #6 has index #1\n #7 has index #4\n #8 has index #7\n #9 has index #12\n #10 has index #14\n #11 has index #16\n #12 has index #17\n #13 has index #10\n #14 has index #11\n #15 has index #13\n #16 has index #5\n #17 has index #2\n</code></pre>\n\n<p>you may as well compare obj1 with obj2 and decide what you want to return\npossible values are: </p>\n\n<ul>\n<li>NSOrderedAscending = -1</li>\n<li>NSOrderedSame = 0</li>\n<li>NSOrderedDescending = 1</li>\n</ul>\n'}, {'answer_id': 10334720, 'author': 'kal', 'author_id': 1358836, 'author_profile': 'https://Stackoverflow.com/users/1358836', 'pm_score': -1, 'selected': False, 'text': '<pre><code>NSUInteger randomIndex = arc4random() % [theArray count];\n</code></pre>\n'}, {'answer_id': 10874468, 'author': 'gregoltsov', 'author_id': 1226722, 'author_profile': 'https://Stackoverflow.com/users/1226722', 'pm_score': 5, 'selected': False, 'text': '<p>Since I can\'t yet comment, I thought I\'d contribute a full response. I modified Kristopher Johnson\'s implementation for my project in a number of ways (really trying to make it as concise as possible), one of them being <code>arc4random_uniform()</code> because it avoids <a href="https://stackoverflow.com/a/7082580/1226722">modulo bias</a>.</p>\n\n<pre><code>// NSMutableArray+Shuffling.h\n#import &lt;Foundation/Foundation.h&gt;\n\n/** This category enhances NSMutableArray by providing methods to randomly\n * shuffle the elements using the Fisher-Yates algorithm.\n */\n@interface NSMutableArray (Shuffling)\n- (void)shuffle;\n@end\n\n// NSMutableArray+Shuffling.m\n#import "NSMutableArray+Shuffling.h"\n\n@implementation NSMutableArray (Shuffling)\n\n- (void)shuffle\n{\n    NSUInteger count = [self count];\n    for (uint i = 0; i &lt; count - 1; ++i)\n    {\n        // Select a random element between i and end of array to swap with.\n        int nElements = count - i;\n        int n = arc4random_uniform(nElements) + i;\n        [self exchangeObjectAtIndex:i withObjectAtIndex:n];\n    }\n}\n\n@end\n</code></pre>\n'}, {'answer_id': 18789993, 'author': 'Denis Kutlubaev', 'author_id': 751641, 'author_profile': 'https://Stackoverflow.com/users/751641', 'pm_score': 2, 'selected': False, 'text': '<p>There is a nice popular library, that has this method as it\'s part, called <a href="https://github.com/soffes/sstoolkit" rel="nofollow">SSToolKit in GitHub</a>. \nFile NSMutableArray+SSToolkitAdditions.h contains shuffle method. You can use it also. Among this, there seem to be tons of useful things. </p>\n\n<p>The main page of this library is <a href="http://sstoolk.it" rel="nofollow">here</a>.</p>\n\n<p>If you use this, your code will be like this: </p>\n\n<pre><code>#import &lt;SSCategories.h&gt;\nNSMutableArray *tableData = [NSMutableArray arrayWithArray:[temp shuffledArray]];\n</code></pre>\n\n<p>This library also has a Pod (see CocoaPods)</p>\n'}, {'answer_id': 22558992, 'author': 'Gamma-Point', 'author_id': 275047, 'author_profile': 'https://Stackoverflow.com/users/275047', 'pm_score': 1, 'selected': False, 'text': '<p>If elements have repeats. </p>\n\n<p>e.g. array: A A A B B or B B A A A</p>\n\n<p>only solution is: A B A B A</p>\n\n<p><code>sequenceSelected</code> is an NSMutableArray which stores elements of class obj, which are pointers to some sequence.</p>\n\n<pre><code>- (void)shuffleSequenceSelected {\n    [sequenceSelected shuffle];\n    [self shuffleSequenceSelectedLoop];\n}\n\n- (void)shuffleSequenceSelectedLoop {\n    NSUInteger count = sequenceSelected.count;\n    for (NSUInteger i = 1; i &lt; count-1; i++) {\n        // Select a random element between i and end of array to swap with.\n        NSInteger nElements = count - i;\n        NSInteger n;\n        if (i &lt; count-2) { // i is between second  and second last element\n            obj *A = [sequenceSelected objectAtIndex:i-1];\n            obj *B = [sequenceSelected objectAtIndex:i];\n            if (A == B) { // shuffle if current &amp; previous same\n                do {\n                    n = arc4random_uniform(nElements) + i;\n                    B = [sequenceSelected objectAtIndex:n];\n                } while (A == B);\n                [sequenceSelected exchangeObjectAtIndex:i withObjectAtIndex:n];\n            }\n        } else if (i == count-2) { // second last value to be shuffled with last value\n            obj *A = [sequenceSelected objectAtIndex:i-1];// previous value\n            obj *B = [sequenceSelected objectAtIndex:i]; // second last value\n            obj *C = [sequenceSelected lastObject]; // last value\n            if (A == B &amp;&amp; B == C) {\n                //reshufle\n                sequenceSelected = [[[sequenceSelected reverseObjectEnumerator] allObjects] mutableCopy];\n                [self shuffleSequenceSelectedLoop];\n                return;\n            }\n            if (A == B) {\n                if (B != C) {\n                    [sequenceSelected exchangeObjectAtIndex:i withObjectAtIndex:count-1];\n                } else {\n                    // reshuffle\n                    sequenceSelected = [[[sequenceSelected reverseObjectEnumerator] allObjects] mutableCopy];\n                    [self shuffleSequenceSelectedLoop];\n                    return;\n                }\n            }\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 26380905, 'author': 'fcortes', 'author_id': 1016865, 'author_profile': 'https://Stackoverflow.com/users/1016865', 'pm_score': -1, 'selected': False, 'text': '<p><a href="https://stackoverflow.com/questions/56648/whats-the-best-way-to-shuffle-an-nsmutablearray#56656">Kristopher Johnson\'s answer</a> is pretty nice, but it\'s not totally random.</p>\n\n<p>Given an array of 2 elements, this function returns always the inversed array, because you are generating the range of your random over the rest of the indexes. A more accurate <code>shuffle()</code> function would be like</p>\n\n<pre><code>- (void)shuffle\n{\n   NSUInteger count = [self count];\n   for (NSUInteger i = 0; i &lt; count; ++i) {\n       NSInteger exchangeIndex = arc4random_uniform(count);\n       if (i != exchangeIndex) {\n            [self exchangeObjectAtIndex:i withObjectAtIndex:exchangeIndex];\n       }\n   }\n}\n</code></pre>\n'}, {'answer_id': 28414220, 'author': 'uucp', 'author_id': 4547023, 'author_profile': 'https://Stackoverflow.com/users/4547023', 'pm_score': -1, 'selected': False, 'text': '<p>Edit: <strong>This is not correct.</strong> For reference purposes, I did not delete this post. See comments on the reason why this approach is not correct.</p>\n\n<p>Simple code here:</p>\n\n<pre><code>- (NSArray *)shuffledArray:(NSArray *)array\n{\n    return [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {\n        if (arc4random() % 2) {\n            return NSOrderedAscending;\n        } else {\n            return NSOrderedDescending;\n        }\n    }];\n}\n</code></pre>\n'}, {'answer_id': 33840745, 'author': 'Cœur', 'author_id': 1033581, 'author_profile': 'https://Stackoverflow.com/users/1033581', 'pm_score': 4, 'selected': False, 'text': '<p>A slightly improved and concise solution (compared to the top answers).</p>\n\n<p>The algorithm is the same and is described in literature as "<a href="https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle" rel="nofollow noreferrer">Fisher-Yates shuffle</a>".</p>\n\n<p>In Objective-C:</p>\n\n<pre><code>@implementation NSMutableArray (Shuffle)\n// Fisher-Yates shuffle\n- (void)shuffle\n{\n    for (NSUInteger i = self.count; i &gt; 1; i--)\n        [self exchangeObjectAtIndex:i - 1 withObjectAtIndex:arc4random_uniform((u_int32_t)i)];\n}\n@end\n</code></pre>\n\n<p>In Swift 3.2 and 4.x:</p>\n\n<pre><code>extension Array {\n    /// Fisher-Yates shuffle\n    mutating func shuffle() {\n        for i in stride(from: count - 1, to: 0, by: -1) {\n            swapAt(i, Int(arc4random_uniform(UInt32(i + 1))))\n        }\n    }\n}\n</code></pre>\n\n<p>In Swift 3.0 and 3.1:</p>\n\n<pre><code>extension Array {\n    /// Fisher-Yates shuffle\n    mutating func shuffle() {\n        for i in stride(from: count - 1, to: 0, by: -1) {\n            let j = Int(arc4random_uniform(UInt32(i + 1)))\n            (self[i], self[j]) = (self[j], self[i])\n        }\n    }\n}\n</code></pre>\n\n<p>Note: <a href="https://stackoverflow.com/a/43801201/1033581">A more concise solution in Swift is possible from iOS10 using <code>GameplayKit</code>.</a></p>\n\n<p>Note: <a href="https://stackoverflow.com/a/31420827/1033581">An algorithm for unstable shuffling (with all positions forced to change if count > 1) is also available</a></p>\n'}, {'answer_id': 40613895, 'author': 'andreacipriani', 'author_id': 872908, 'author_profile': 'https://Stackoverflow.com/users/872908', 'pm_score': 4, 'selected': False, 'text': '<p>If you import <code>GameplayKit</code>, there is a <code>shuffled</code> API:</p>\n\n<p><a href="https://developer.apple.com/reference/foundation/nsarray/1640855-shuffled" rel="nofollow noreferrer">https://developer.apple.com/reference/foundation/nsarray/1640855-shuffled</a></p>\n\n<pre><code>let shuffledArray = array.shuffled()\n</code></pre>\n'}, {'answer_id': 43801201, 'author': 'Cœur', 'author_id': 1033581, 'author_profile': 'https://Stackoverflow.com/users/1033581', 'pm_score': 2, 'selected': False, 'text': '<p>From iOS 10, you can use <a href="https://developer.apple.com/reference/foundation/nsarray/1640855-shuffled" rel="nofollow noreferrer">NSArray <code>shuffled()</code> from GameplayKit</a>. Here is an helper for Array in Swift 3:</p>\n\n<pre><code>import GameplayKit\n\nextension Array {\n    @available(iOS 10.0, macOS 10.12, tvOS 10.0, *)\n    func shuffled() -&gt; [Element] {\n        return (self as NSArray).shuffled() as! [Element]\n    }\n    @available(iOS 10.0, macOS 10.12, tvOS 10.0, *)\n    mutating func shuffle() {\n        replaceSubrange(0..&lt;count, with: shuffled())\n    }\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/56648', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1175/']