可能重複:
Is this C implementation of Fisher-Yates shuffle correct?隨機化序列
爲了模擬不同的順序輸入序列的成我的應用程序,我想以產生用於隨機化序列的列表一個數組輸入。例如,給定一個arr [10],默認序列是0,1,...,8,9。但是,我想操作順序爲隨機順序,例如,2,4,5,1,9,0,3,7,8,6。
我認爲rand()會生成一個0-9之間的隨機值,但它不能保證每個元素至少生成一次。在這種情況下,我正在考慮低於僞,但有沒有更好的方法來生成隨機輸入序列,並確保給定範圍內的每個數字至少生成一次?
round #1:
generate a random number within 0-9.
let say 2 is selected
round #2:
generate a random number within 0-1
generate a random number within 3-9
let say 0 and 4 are selected
round #3:
generate a random number within 1
generate a random number within 3
generate a random number within 5-9
let say 1, 3, 7 are selected
round #4:
generate a random number within 5-6
generate a random number within 8-9
continue until 10 numbers are selected
生成序列0 - 9並洗牌,最好用Fisher-Yates。 – Jon 2012-07-13 07:31:59