2010-11-17 13 views

Respuesta

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

mejor solución si orienta su aplicación para iOS> = 4.3. '__OSX_AVAILABLE_STARTING (__ MAC_10_7, __IPHONE_4_3)' – Hemang

+0

¿Por qué se itera desde n -> 0 y no 0 -> n –

+0

@ Peter Se repite hacia atrás porque no quiere obtener el conteo en cada iteración y la dirección no importa ya que estamos aleatorizando de todos modos. Mantiene la cuenta regresiva de la línea. –

Cuestiones relacionadas