Quantcast
Channel: CoderzHeaven
Viewing all articles
Browse latest Browse all 526

Random Integer array without repetition in Objective C Iphone

$
0
0

This sample code generates a random number and checks whether its already present in the array.
If yes then it will not add else it will add, thus generating a random array without duplicates.

-(NSMutableArray *) generateRandomArray : (int) max{
    NSMutableArray *randArray = [NSMutableArray new];
    for (int k = 0; k < max; k++) {
       int r = arc4random() % max;
        if([randArray containsObject:[NSString stringWithFormat:@"%d", r]]){
            k--;
        }else{
            [randArray addObject:[NSString stringWithFormat:@"%d", r]];
        }
    }
    NSLog(@"RAND %@",randArray);
    return randArray;
}

Please leave your valuable comments if you found this post useful.


Viewing all articles
Browse latest Browse all 526

Trending Articles