问题
I want to get random object from array, is there any way how can I find random object from mutable array?
回答1:
@interface NSArray (Random)
- (id) randomObject;
@end
@implementation NSArray (Random)
- (id) randomObject
{
if ([self count] == 0) {
return nil;
}
return [self objectAtIndex: arc4random() % [self count]];
}
@end
回答2:
id obj;
int r = arc4random() % [yourArray count];
if(r<[yourArray count])
obj=[yourArray objectAtIndex:r];
else
{
//error message
}
回答3:
id randomObject = nil;
if ([array count] > 0){
int randomIndex = arc4random()%[array count];
randomObject = [array objectAtIndex:randomIndex];
}
回答4:
The best way would be to do something like this
int length = [myMutableArray count];
// Get random value between 0 and 99
int randomindex = arc4random() % length;
Object randomObj = [myMutableArray objectAtIndex:randomindex];
回答5:
Just Copy and Paste
-(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;
}
Note: Count = number of random values you want to fetch
回答6:
Here's a Swift solution using an extension on Arrays:
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]
}
}
You can use it as simple as this:
let digits = Array(0...9)
digits.sample() // => 6
If you prefer a Framework that also has some more handy features then checkout HandySwift. You can add it to your project via Carthage then use it exactly like in the example above:
import HandySwift
let digits = Array(0...9)
digits.sample() // => 8
回答7:
If you don't want to extend NSArray this will get a random value from a given array in one line:
id randomElement = [myArray objectAtIndex:(arc4random() % myArray.count)];
来源:https://stackoverflow.com/questions/7580354/get-random-object-from-array