Get random object from Array

2020-02-04 10:48发布

I want to get random object from array, is there any way how can I find random object from mutable array?

7条回答
Summer. ? 凉城
2楼-- · 2020-02-04 11:30

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

查看更多
乱世女痞
3楼-- · 2020-02-04 11:33

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
查看更多
祖国的老花朵
4楼-- · 2020-02-04 11:34
@interface NSArray (Random)
- (id) randomObject;
@end

@implementation NSArray (Random)

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

@end
查看更多
唯我独甜
5楼-- · 2020-02-04 11:38

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];
查看更多
再贱就再见
6楼-- · 2020-02-04 11:43
id obj;    
int r = arc4random() % [yourArray count];
    if(r<[yourArray count])
      obj=[yourArray objectAtIndex:r];
   else
   {
     //error message
   }
查看更多
Luminary・发光体
7楼-- · 2020-02-04 11:47
id randomObject = nil;
if ([array count] > 0){
    int randomIndex = arc4random()%[array count];
    randomObject = [array objectAtIndex:randomIndex];
}
查看更多
登录 后发表回答