z22
z22

Reputation: 10083

iOS: generate random array between a specific range

I have an array with 80 objects of json. I want to build a new subarray that has only 4 elements(but different everytime filled from the bigger array of 80 elements) with only a particular key of that json.

Following is my code for this:

[arr_sub removeAllObjects];
    [arr_sub addObject:[[arr_main objectAtIndex:currentcount] valueForKey:@"e"]];
    for(int i =1;i<=3;i++)
    {
       //int random = number between 1 to 80 -- how do i generate this ??
        [arr_sub addObject:[[arr_main objectAtIndex:random] valueForKey:@"e"]];
    }

How do I generate a random index between 0 to 79?

Upvotes: 0

Views: 208

Answers (3)

zaph
zaph

Reputation: 112855

To generate a random index in a range use arc4random_uniform(range). In your case:

int random = arc4random_uniform(80);

Use arc4random_uniform() instead of arc4random(), it does not have a bias as with using the mod operator. Also never use the C function rand() because it's result is not random.

But where is the JSON? JSON is a transport representation, in Objective-C the main collection classes are NSArray and NSDictionary. Received JSON is converted into a combination of these usually with the class NSJSONSerialization and a method such as:

+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error

Upvotes: 2

Apurv
Apurv

Reputation: 17186

arc4random is the function using which you can generate the random numbers.

int randomNumber = arc4random()%80;

Upvotes: 1

gran33
gran33

Reputation: 12991

arc4random() Will generate random number between 0-1, U can use it like this:

int min = 0;
int max = 80;

int randNum = arc4random() % (max - min) + min;

Upvotes: 2

Related Questions