如何使用While循环来防止Xcode中随机数相同的数字?

时间:2011-07-23 14:54:45

标签: xcode nsmutablearray arc4random

我希望它能不断产生不同的随机数。如何使用While语句?

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]];

2 个答案:

答案 0 :(得分:1)

也许是这样的。它会循环,直到找到一个不在数组中的数字。

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]];

如果你需要大量的随机数,你可以将整个事物放入另一个循环中,这个循环运行多次,因为你需要不同的数字。

答案 1 :(得分:0)

NSMutableSet不允许重复。

    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.