2010-11-17 15 views

risposta

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

migliore soluzione se si target la vostra applicazione iOS> = 4.3. '__OSX_AVAILABLE_STARTING (__ MAC_10_7, __IPHONE_4_3)' – Hemang

+0

perché si itera da n -> 0 e non 0 -> n –

+0

@Peter Si itera all'indietro perché non vuole ottenere il conteggio ad ogni iterazione e la direzione non ha importanza dato che lo stiamo randomizzando comunque. Mantiene il conto alla rovescia. –

Problemi correlati