gpt4 book ai didi

ios - 使用 arc4random 的更好方法

转载 作者:行者123 更新时间:2023-11-29 02:22:51 25 4
gpt4 key购买 nike

我有一个随机方法来创建 2 个随机整数。我担心的是 %65-%70 的输出是相同的整数,例如“5-5”“4-4”“3-3”。

-(void)random{
NSUInteger randomNumber = arc4random_uniform(5);

switch (randomNumber) {
case 0:
_tile2.image = [UIImage imageNamed:@"one.png"];
break;

case 1:
_tile2.image = [UIImage imageNamed:@"two.png"];
break;

case 2:
_tile2.image = [UIImage imageNamed:@"three.png"];
break;

case 3:
_tile2.image = [UIImage imageNamed:@"four.png"];
break;

case 4:
_tile2.image = [UIImage imageNamed:@"five.png"];
break;
}

NSUInteger randomNumber2 = arc4random_uniform(5);

switch (randomNumber2) {
case 0:
_tile3.image = [UIImage imageNamed:@"one.png"];
break;

case 1:
_tile3.image = [UIImage imageNamed:@"two.png"];
break;

case 2:
_tile3.image = [UIImage imageNamed:@"three.png"];
break;

case 3:
_tile3.image = [UIImage imageNamed:@"four.png"];
break;

case 4:
_tile3.image = [UIImage imageNamed:@"five.png"];
break;
}
}

我应该创建 25 个不同的案例以获得更好的结果吗?

NSUInteger randomNumber = arc4random_uniform(25);

switch (randomNumber) {
case 0:
_tile2.image = [UIImage imageNamed:@"one.png"];
_tile3.image = [UIImage imageNamed:@"one.png"];
break;

case 1:
_tile2.image = [UIImage imageNamed:@"one.png"];
_tile3.image = [UIImage imageNamed:@"two.png"];
break;

case 2:
_tile2.image = [UIImage imageNamed:@"one.png"];
_tile3.image = [UIImage imageNamed:@"three.png"];
break;

case 3:
_tile2.image = [UIImage imageNamed:@"one.png"];
_tile3.image = [UIImage imageNamed:@"four.png"];
break;

case 4:
_tile2.image = [UIImage imageNamed:@"one.png"];
_tile3.image = [UIImage imageNamed:@"five.png"];
break;

case 5:
_tile2.image = [UIImage imageNamed:@"two.png"];
_tile3.image = [UIImage imageNamed:@"one.png"];
break;

...
}
}

arc4random_uniform 非常适合获取一个随机整数。当我需要获得 2 个或更多随机数时,输出并不是那么好。这样做的最佳方法是什么?

最佳答案

对不起,我不相信你。你一定在做一些与你所展示的不同的事情。粘贴到 Playground 中的以下代码始终给出 20% 左右的匹配度,而不是您声称的 65-70%:

import Cocoa

let sampleSize = 1000
var count = 0
for i in 1...sampleSize {
var randomNumber1 = arc4random_uniform(5)
var randomNumber2 = arc4random_uniform(5)
if randomNumber1 == randomNumber2 {
++count
}
}
println( Double(count) / Double(sampleSize) )

无论您遇到什么问题,都与 arc4random_uniform 如何生成值对无关。

关于ios - 使用 arc4random 的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27922601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com