2011-09-28 18 views
13

Voglio ottenere un oggetto casuale dall'array, esiste un modo come posso trovare un oggetto casuale dall'array mutabile?Ottieni oggetto casuale dalla matrice

+0

possibile duplicato di [come accedere agli elementi randon da una matrice in telefono i sdk] (http: // StackOverflow .com/questions/3509411/how-to-access-randon-items-da-un-array-in-i-phone-sdk) –

risposta

33
@interface NSArray (Random) 
- (id) randomObject; 
@end 

@implementation NSArray (Random) 

- (id) randomObject 
{ 
    if ([self count] == 0) { 
     return nil; 
    } 
    return [self objectAtIndex: arc4random() % [self count]]; 
} 

@end 
+1

Per evitare il bias del modulo, piuttosto che arc4random() usare arc4random_uniform(). (Per ulteriori informazioni, consultare http://stackoverflow.com/questions/10984974/why-do-people-say-there-is-modulo-bias-when-using-a-random-number-generator). –

8
id obj;  
int r = arc4random() % [yourArray count]; 
    if(r<[yourArray count]) 
     obj=[yourArray objectAtIndex:r]; 
    else 
    { 
    //error message 
    } 
+0

Cosa ne pensi di 'else'? – Thilo

+1

@ Thilo, in caso contrario qualsiasi messaggio o quant'altro richiesto. – Ishu

7
id randomObject = nil; 
if ([array count] > 0){ 
    int randomIndex = arc4random()%[array count]; 
    randomObject = [array objectAtIndex:randomIndex]; 
} 
3

Il modo migliore sarebbe quello di fare qualcosa di simile

int length = [myMutableArray count]; 
// Get random value between 0 and 99 
int randomindex = arc4random() % length; 

Object randomObj = [myMutableArray objectAtIndex:randomindex]; 
0

Se non si desidera estendere NSArray questo otterrà un valore casuale da un dato array in una riga:

id randomElement = [myArray objectAtIndex:(arc4random() % myArray.count)]; 
1

Solo Copia e Incolla

-(NSMutableArray*)getRandomValueFromArray:(NSMutableArray*)arrAllData randomDataCount:(NSInteger)count { 
NSMutableArray *arrFilterData = [[NSMutableArray alloc]init]; 
for(int i=0; i<count; i++){ 

    NSInteger index = arc4random() % (NSUInteger)(arrAllData.count); 
    [arrFilterData addObject:[arrAllData objectAtIndex:index]]; 
    [arrAllData removeObjectAtIndex:index]; 
} 
return arrFilterData; 
} 

Nota: Count = numero di valori casuali che si desidera recuperare

1

Ecco una soluzione Swift utilizzando un'estensione su array:

extension Array { 
    func sample() -> Element? { 
     if self.isEmpty { return nil } 
     let randomInt = Int(arc4random_uniform(UInt32(self.count))) 
     let randomIndex = self.startIndex.advancedBy(randomInt) 
     return self[randomIndex] 
    } 
} 

si può utilizzare Semplice come questo:

let digits = Array(0...9) 
digits.sample() // => 6 

Se si preferisce un quadro che ha anche alcune caratteristiche più a portata di mano quindi checkout HandySwift. È possibile aggiungere al progetto via Cartagine poi usarlo esattamente come nell'esempio di cui sopra:

import HandySwift  

let digits = Array(0...9) 
digits.sample() // => 8