Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get random object from Array

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

like image 763
Sonu Avatar asked Sep 28 '11 08:09

Sonu


People also ask

How do you generate a random element from an array in Python?

Use the numpy.random.choice() function to generate the random choices and samples from a NumPy multidimensional array. Using this function we can get single or multiple random numbers from the n-dimensional array with or without replacement.

How do you generate a random value from an array in Java?

nextInt() method of Random class can be used to generate a random value between 0 and the size of ArrayList. Now use this number as an index of the ArrayList. Use get () method to return a random element from the ArrayList using number generated from nextInt() method.

How do you select a random item from a list in Java?

Picking a Random Item/Items In order to get a random item from a List instance, you need to generate a random index number and then fetch an item by this generated index number using List. get() method. The key point here is to remember that you mustn't use an index that exceeds your List's size.


1 Answers

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

@implementation NSArray (Random)

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

@end
like image 130
zoul Avatar answered Oct 02 '22 19:10

zoul