Random Integer array without repetition in Objective C Iphone

By | February 20, 2014

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.

Leave a Reply

Your email address will not be published. Required fields are marked *