我有一个随机方法来创建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个或更多随机数时,输出不是那么好。这样做的最佳方式是什么?
答案 0 :(得分:1)
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
生成价值对。
答案 1 :(得分:0)
使用一组数字是否适合您? 你可以有一个可变的数字数组`[@ 0,@ 1,@ 2,@ 3,@ 4]并从随机索引中检索一个数字
NSMutableArray *array = [NSMutableArray arrayWithObjects:@0, @1, @2, @3, @4];
NSInteger firstIndex = arc4random_uniform([array count]);
NSNumber *firstNumber = array[index];
删除您刚刚找到的号码:
[array removeObjectAtIndex:firstIndex];
而不是重复第二个数字。第一个检索到的号码不再在阵列中,所以即使arc4random_uniform()
给你相同的值(你的65-70%的情况),你将在你的开关盒中使用的实际数字是&#39 ;会有所不同。
这种方法可能有点笨拙,但我认为它可以帮助您对随机性进行一些控制。