简体   繁体   中英

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?

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;

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

arc4random是用于生成随机数的函数。

int randomNumber = arc4random()%80;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM