2011-04-14 94 views

回答

12

類別添加到NSMutableArray裏,與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 
+0

謝謝你的回答。 – Hariprasad 2011-04-14 07:37:11

+0

這是重複數組元素 – 2012-07-20 05:05:04

+13

複製其他人的答案是不好的做法: pasawaya 2012-11-02 16:46:02