我试图用随机序列填充数字从1-20的20个整数的数组。 这里是我的代码:用随机数填充数组
int lookup[20]={0};
int array[20]={0};
srand(time(NULL));
for(int i=0;i<20;++i){
bool done=false;
while(!done){
int n=rand()%20;
if(lookup[n]==0){
array[i]=n;
lookup[n]=1;
done=true;
}
}
}
我创建了一个查找数组来检查,如果还没有选择,并将其存储在数组中的随机数。正如你所看到的,我创建了2个循环,一个用于遍历数组,另一个用于选择随机数。在每个while循环迭代中,该数字可能会重新出现并导致另一个while循环。有没有更快的方法来做到这一点?
apply random-number-generator tag – 2010-03-03 10:02:49
另见:http://stackoverflow.com/questions/1218155/random-number-but-dont-repeat,http://stackoverflow.com/questions/1816534/random -playlist-algorithm,http://stackoverflow.com/questions/417831/what-is-the-best-way-of-randomly-re-arranging-a-list-of-items-in-c,http:/ /stackoverflow.com/questions/813935/randomizing-elements-in-an-array – outis 2010-03-03 14:07:16