我試圖用隨機序列填充數字從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