2010-11-17 5 views

Répondre

55
NSUInteger count = [yourMutableArray 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 = (arc4random() % nElements) + i; 
    [yourMutableArray exchangeObjectAtIndex:i withObjectAtIndex:n]; 
} 
25
// the Knuth shuffle 
for (NSInteger i = array.count-1; i > 0; i--) 
{ 
    [array exchangeObjectAtIndex:i withObjectAtIndex:arc4random_uniform(i+1)]; 
} 
+0

La meilleure solution si vous ciblez votre application iOS> = 4.3. '__OSX_AVAILABLE_STARTING (__ MAC_10_7, __IPHONE_4_3)' – Hemang

+0

Pourquoi itérez-vous de n -> 0 et non 0 -> n –

+0

@Peter He itère en arrière car il ne veut pas obtenir le nombre à chaque itération et la direction n'a pas d'importance puisque nous le randomisons quand même. Garde le compte à rebours. –