Thursday, September 12, 2013

Random Number Array in Objective C

Hi, i think this is a common and basic requirement for every developer in each field, to get the Random numbers in Array. I have made a function to simplify this logic in Objective C.
So here is the code if this
-(void) checkExistance:(int) max
    int value = [self randomNumberFrom:0 to:max];//Modify according to minimum /maximum value in Array
    int i = 0;
    for (i = 0; i < [self.numbers count]; i++)
        if ([[self.numbers objectAtIndex:i] integerValue] == value)
    if (i == [self.numbers count])
        [self.numbers addObject:[NSNumber numberWithInt:value]];
    if ([self.numbers count] != max)
        [self checkExistance:max];
- (int) randomNumberFrom: (int) minValue to: (int) maxValue
    int rangeValue = maxValue - minValue;
    return (arc4random() % rangeValue) + minValue;


You just need to call checkExistance method with passing a maximum value in this. You can modify your code for minimum and maximum as well in this. 

Now just call

[self checkExistance:6];

and you will see the result by following

for(int j = 0;j<self.numbers.count;j++)
    NSLog(@" %@", [self.numbers objectAtIndex:j]);