在 arc4random() 数字上使用一次
如何编写不重复数字两次的 arc4random() 代码?
例如。我用的是开关和按钮。我不想再次生成重复使用的相同 arc4random 数。如果我有 arc4random,生成编号为 2,4,42,32,42... 我不想42再次出现。
我该如何避免这种情况?
switch (arc4random() % 50 )
{
case 1:
text.text = @"You are silly boy";
break;
case 2:
text.text = @"Well, you very very silly"];
break;
case 3:
text.text = @"stop being silly"];
break;
case 4:
[text.text = @"silly... silly"];
break;
case 5:
text.text = @"what you silly boy"];
break;
...
case 0:
text.text = @"you silly"];
break;
}
How you code arc4random() that does not repeat number twice?
For instance. I'm using switch and button. I don't want to generate reused the same arc4random number again. If I have arc4random that generation numbers 2,4,42,32,42...
I don't want to 42 to appear again.
How do I avoid this?
switch (arc4random() % 50 )
{
case 1:
text.text = @"You are silly boy";
break;
case 2:
text.text = @"Well, you very very silly"];
break;
case 3:
text.text = @"stop being silly"];
break;
case 4:
[text.text = @"silly... silly"];
break;
case 5:
text.text = @"what you silly boy"];
break;
...
case 0:
text.text = @"you silly"];
break;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
arc4random() 不是重复生成器,即每次调用都独立于所有其他调用。但这也意味着仅调用 arc4random() 不会(通常)生成 50 个唯一数字。
一种方法是创建一个所需整数的数组,然后遍历该数组并将每个数组与随机选择的另一个(在您的情况下)用 (arc4random() % 50) 交换。他们只是使用数组中的连续值,最后创建一个新数组并将其随机化。
示例:列表中的值将是 0 到 49 之间的随机数,不重复:
这是 Fisher-Yates 洗牌的现代版本,专为计算机使用而设计,由 Richard Durstenfeld 引入。
注意:使用 mod 创建子集会产生偏差,但在 50 的情况下,偏差可以忽略不计。
arc4random()
is not a repeating generator, that is each invocation is independent of all other invocation. But that also means that just invokingarc4random()
will not (generally) produce 50 unique numbers.One way is to create an array of the integers you want and then walk through the array and swap each one with another chosen at random (in your case) with (arc4random() % 50). They just use consecutive values from the array and when at the end create a new array and randomize it.
Example: The values in the list will be random numbers between 0 and 49 with no repeats:
This is the modern version of the Fisher–Yates shuffle, designed for computer use and introduced by Richard Durstenfeld.
Note: using mod to create a subset creates a bias but in a case of 50 the bias is negligible.
一种方法如下:
此代码始终在每次调用时切换到唯一的情况。代码的工作方式是在每次调用时将
arc4random()
的范围减小 1。更新: 请注意,此方法更偏向于运行结束时较小的数字范围。所以这不是真正的非重复随机数生成。但如果这不是问题,那么它是一个很容易包含在代码中的行。
One way of doing it would be as follows:
This code always switches to a unique case on each invocation. The way the code works is by decreasing the range of
arc4random()
at each invocation by 1.Update: Keep note that this method biases more towards the end of the run to a smaller range of numbers. So this is not a true non-repeating random number generation. But if thats not a concern, its an easy one liner to include in your code.