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

发布于 2024-11-26 01:18:06 字数 375 浏览 0 评论 0原文

我希望它不断生成不同的随机数。如何使用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]];

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小霸王臭丫头 2024-12-03 01:18:06

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

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

如果您需要大量随机数,您可以将整个过程放入另一个循环中,该循环根据您需要的不同数字运行多少轮。

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.

迷爱 2024-12-03 01:18:06

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.

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.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文