2011-06-06 101 views

回答

15

以下是一些示例代碼: 遍歷數組,並隨機將對象的位置與另一個對象切換。

for (int x = 0; x < [array count]; x++) { 
    int randInt = (arc4random() % ([array count] - x)) + x; 
    [array exchangeObjectAtIndex:x withObjectAtIndex:randInt]; 
} 
+1

謝謝你爲這個簡單的代碼。有用。我喜歡你。 – GeneCode 2013-01-04 17:46:48

4
@interface NSArray (Shuffling) 

- (NSArray *)shuffledArray; 

@end 

@implementation NSArray (Shuffling) 

- (NSArray *)shuffledArray { 
    NSMutableArray *newArray = [[self mutableCopy] autorelease]; 

    [newArray shuffle]; 
    return newArray; 
} 

@end 

@interface NSMutableArray (Shuffling) 

- (void)shuffle; 

@end 

@implementation NSMutableArray (Shuffling) 

- (void)shuffle { 
    @synchronized(self) { 
     NSUInteger count = [self count]; 

     if (count == 0) { 
      return; 
     } 

     for (NSUInteger i = 0; i < count; i++) { 
      NSUInteger j = arc4random() % (count - 1); 

      if (j != i) { 
       [self exchangeObjectAtIndex:i withObjectAtIndex:j]; 
      } 
     } 
    } 
} 

@end 

但是請記住,這種洗牌是merely pseudorandom洗牌