Shishir.bobby
Shishir.bobby

Reputation: 10984

How to check unique int number in iphone

How can we check if the number generated through I am trying to generate a unique number in between 0 to 10.

randomNumber = arc4random() % 10;

is unique or not??

i am able to generate a random number, but not able to check,whether its unique or not?

Thanks

Upvotes: 0

Views: 91

Answers (3)

Chetan9007
Chetan9007

Reputation: 908

Try this code...this will give you all the possible unique number set in Mutable array...

-(NSInteger) randomNumber {
NSInteger newRandomNumber = (NSInteger) arc4random() % 10;
NSInteger uniqueNumber;
if ([self.arrayContainingNumbers containsObject: [NSNumber numberWithInteger:newRandomNumber]]) {
    [self randomNumber];
    } else {
    [self.arrayContainingNumbers addObject: [NSNumber numberWithInteger:newRandomNumber]];
}
uniqueNumber = [[self.mutableArrayContainingNumbers lastObject]integerValue];
     NSLog(@"new Unique Number is %ld",(long)uniqueNumber);

return uniqueNumber;  }

Don't forget to add this method :)

-(NSMutableArray *) arrayContainingNumbers {
if (!_mutableArrayContainingNumbers) {
    _mutableArrayContainingNumbers = [[NSMutableArray alloc] init];
}
return _mutableArrayContainingNumbers; }

Upvotes: 0

bitmapdata.com
bitmapdata.com

Reputation: 9600

To avoid duplication, refer a following random number generation code. When you run the following code also does not overlap any number. If you mean you want it unique.

#define COUNT 1000
#define RANGE 1000
int num[COUNT];

bool isNew(int idx, int val)
{
    for (int i=0; i<idx; i++) 
    {
        if (num[i] == val) return false;
    }
    return true;
}

for (int i=0; i<COUNT; i++)
{
    do
    {
        num[i]=arc4random()%RANGE;        
    }
    while (!isNew(i, num[i]));
    NSLog(@"%d ", num[i]);
}    

Upvotes: 3

Christian Pappenberger
Christian Pappenberger

Reputation: 359

You can save all generated numbers in an array and check whether there are two duplicates.

The more number you have, the more is sure that the generated numbers are unique.

Upvotes: 1

Related Questions