可能重複:
What’s the Best Way to Shuffle an NSMutableArray?洗牌在Objective-C數組
我開發iPhone/iPad.I的應用程序要重新洗牌存儲在NSArray.Is有任何對象用objective-c實現它的方法?
可能重複:
What’s the Best Way to Shuffle an NSMutableArray?洗牌在Objective-C數組
我開發iPhone/iPad.I的應用程序要重新洗牌存儲在NSArray.Is有任何對象用objective-c實現它的方法?
類別添加到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
看看這個sample有幫助。
你可以看到這個以前的SO問題太canonical way to randomize an NSArray in Objective C
謝謝了voteup此信息。 – Hariprasad 2011-04-14 07:36:41
謝謝你的回答。 – Hariprasad 2011-04-14 07:37:11
這是重複數組元素 – 2012-07-20 05:05:04
複製其他人的答案是不好的做法: –
pasawaya
2012-11-02 16:46:02