Shuffling an array in objective-c

14,297

Solution 1

Add a category to NSMutableArray, with code provided by Kristopher Johnson -

//  NSMutableArray_Shuffling.h

#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#else
#include <Cocoa/Cocoa.h>
#endif

// This category enhances NSMutableArray by providing
// methods to randomly shuffle the elements.
@interface NSMutableArray (Shuffling)
- (void)shuffle;
@end


//  NSMutableArray_Shuffling.m

#import "NSMutableArray_Shuffling.h"

@implementation NSMutableArray (Shuffling)

- (void)shuffle
{

  static BOOL seeded = NO;
  if(!seeded)
  {
    seeded = YES;
    srandom(time(NULL));
  }

    NSUInteger count = [self count];
    for (NSUInteger i = 0; i < count; ++i) {
        // Select a random element between i and end of array to swap with.
        int nElements = count - i;
        int n = (random() % nElements) + i;
        [self exchangeObjectAtIndex:i withObjectAtIndex:n];
    }
}

@end

Solution 2

See if this sample helps.

You can see this previous SO question too canonical way to randomize an NSArray in Objective C

Share:
14,297

Related videos on Youtube

Hariprasad
Author by

Hariprasad

Updated on June 04, 2022

Comments

  • Hariprasad
    Hariprasad almost 2 years

    Possible Duplicate:
    What’s the Best Way to Shuffle an NSMutableArray?

    I develop apps for iphone/iPad.I want to shuffle the objects stored in an NSArray.Is there any way to achieve it with objective-c?

  • Hariprasad
    Hariprasad about 13 years
    Thank you,a voteup for this info.
  • Vineesh TP
    Vineesh TP almost 12 years
    It is repeating array elements
  • pasawaya
    pasawaya over 11 years
    It's not good practice to copy someone else's answer: <stackoverflow.com/questions/56648/…>
  • kevinthompson
    kevinthompson almost 10 years
    Note that the original answer has been improved, so use it rather than this old copy of the original. See stackoverflow.com/questions/56648/…

Related