开发者

Random number generating unique numbers in Objective-C?

I want to generate random numbers between 1-100 in Objective-C. Each random number should be unique and not the same开发者_JAVA技巧 as a previously generated random number.


Check this links

  • Generating Random Numbers in Objective-C

  • How do I generate random numbers on the iPhone?

    int r = arc4random() % 100;
    

  • Objective-C: Get random number

    -(int)getRandomNumberBetween:(int)from and:(int)to {
    
        return (int)from + arc4random() % (to-from+1);
    }
    

    How to use:

    1) Implement method above into your .m file

    2) Add the following line to your .h file:

    -(int)getRandomNumberBetween:(int)from and:(int)to;
    

    3) Call the method like:

    int randomNumber = [self getRandomNumberBetween:9 and:99];
    //this gets you a random number between 9 and 99
    

  • Random Numbers in Objective-C


arc4random() %(100)-1 this is worked for me.


Use arc4random and store the results in an NSSet which will take care of the duplicates for you.


An other easy way is to do this is the use the arc4random_uniform() method:

Calling arc4random_uniform(N) return a random number from 0 to N-1. To get a number from 1 to N, you can use:

NSUInteger r = arc4random_uniform(N) + 1;

where N is the max number that you are looking for. In Swift, you can do it as:

var randomIndex:UInt32 = arc4random_uniform(N) + 1

e.g. if you want to get a random number between 1 and 100, just call as:

NSUInteger r = arc4random_uniform(100) + 1;

or in swift:

var randomIndex:UInt32 = arc4random_uniform(100)+1


This is the code which generate unique random numbers...

-(void)UniqueRandom{

    int T[11];
    BOOL flag;
    for(int i=0;i<10;i++){

        int ranNo=  random()%100+1;
        flag=TRUE;
        int s=(sizeof T); 

        for(int x=0;x<s;x++){

            if(ranNo==T[x]){
                i--;
                flag= FALSE;
                break;
            }
        }

        if(flag) T[i]=ranNo;
    }

    for(int j=0;j<100;j++)  NSLog(@"unique random %d",T[j]);
    }
}

Happy coding..


This method will generate array of unique random number in the interval of high and low range.

-(void)generateRandomUniqueNumberInRange :(int)rangeLow :(int)rangeHigh{
    NSMutableArray *unqArray=[[NSMutableArray alloc] init];
    int randNum = arc4random() % (rangeHigh-rangeLow+1) + rangeLow;
    int counter=0;
    while (counter<rangeHigh-rangeLow) {
        if (![unqArray containsObject:[NSNumber numberWithInt:randNum]]) {
            [unqArray addObject:[NSNumber numberWithInt:randNum]];
            counter++;
        }else{
            randNum = arc4random() % (rangeHigh-rangeLow+1) + rangeLow;
        }

    }
    NSLog(@"UNIQUE ARRAY %@",unqArray);

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜