J'utilise NSArray/NSMutable array pour stocker différents objets. Une fois tous les objets ajoutés, je veux les réarranger dans un ordre aléatoire. Comment puis-je le faire?Réorganiser NSArray/MSMutableArray dans un ordre aléatoire
14
A
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)];
}
La meilleure solution si vous ciblez votre application iOS> = 4.3. '__OSX_AVAILABLE_STARTING (__ MAC_10_7, __IPHONE_4_3)' – Hemang
Pourquoi itérez-vous de n -> 0 et non 0 -> n –
@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. –