开发者

How to use While loop to prevent the same number in random number in Xcode?

I want it keeps generating different random number. How to use While statement?

int randomnumber = (arc4random() % 188)+1; 

if ([myArray containsObject:[NSNumber numberWithInt:randomnumber]])
{
    NSLog(@"Yes, they are the same");
    randomnumber =开发者_开发百科 (arc4random() % 188)+1;
}
else
{
    NSLog(@"No, they are not the same");
        }
[myArray addObject:[NSNumber numberWithInt:randomnumber]];


Maybe something like this. It loops until it finds a number that's not in the array.

int randomnumber = (arc4random() % 188)+1; 

while ([myArray containsObject:[NSNumber numberWithInt:randomnumber]])
{
    NSLog(@"Yes, they are the same");
    randomnumber = (arc4random() % 188)+1;
}

[myArray addObject:[NSNumber numberWithInt:randomnumber]];

If you need lots of random numbers, you can put the whole thing into another loop that runs for as many rounds as you need distinct numbers.


NSMutableSet wont allow dublicate.

    NSMutableSet * numberWithSet = [[NSMutableSet alloc]initWithCapacity:20]

    while ([numberWithSet count] < 20 ) {

        NSNumber * randomNumber = [NSNumber numberWithInt:(arc4random() % 23 + 1)];

        [numberWithSet addObject:randomNumber];

    }

        NSLog(@"numberWithSet : %@ \n\n",numberWithSet);

    [numberWithSet release];

    `arc4random() % 22 + 1` will give you numbers between 1 and 22 including both of them but not 23.
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜