【发布时间】:2012-08-24 12:32:39
【问题描述】:
我有整数,即 0、17、23、44、57、60、66、83、89、91、100,但我想从该数字中随机取 6 个数字,该怎么做?我只能显示 0-100 之间的一个随机数,但我不知道如何从选定的数字中显示 6 个数字。请教。
【问题讨论】:
-
那些整数值是否插入到数组中?
我有整数,即 0、17、23、44、57、60、66、83、89、91、100,但我想从该数字中随机取 6 个数字,该怎么做?我只能显示 0-100 之间的一个随机数,但我不知道如何从选定的数字中显示 6 个数字。请教。
【问题讨论】:
如果您想从数组中挑选六个不重复的数字,请使用Knuth-Fisher–Yates shuffle 打乱数组,然后取前六个数字:
int data[] = {0, 17, 23, 44, 57, 60, 66, 83, 89, 91, 100};
// Knuth-Fisher-Yates
for (int i = 10 ; i > 0 ; i--) {
int n = rand() % (i+1);
int tmp = data[i];
data[i] = data[n];
data[n] = tmp;
}
data 数组的前六个元素包含从原始 11 元素数组中的随机选择。
【讨论】:
将数字放入数组中。使用随机数生成器获取小于数组长度 0 到 1 之间的随机数,然后获取该索引处的数字。
这只是一种方法。
【讨论】:
对于将随机数提取到数组中,以下代码可能对您有用
[array objectAtIndex: (random() % [array count])]
这是一个例子
NSUInteger firstObject = 0;
for (int i = 0; i<[myNSMutableArray count];i++) {
NSUInteger randomIndex = random() % [myNSMutableArray count];
[myNSMutableArray exchangeObjectAtIndex:firstObject withObjectAtIndex:randomIndex];
firstObject +=1;
}
【讨论】:
看到这个帖子:Generating random numbers in Objective-C
有很多方法可以做到这一点。这种特殊的方法有很好的反应。要获得 6 个随机数,只需运行该函数 6 次。
【讨论】: