0

可能重复:
Fisher-Yates shuffle 的这个 C 实现是否正确?

为了在我的应用程序中模拟不同顺序的输入序列,我想为数组输入生成一个随机序列列表。例如,给定 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
4

2 回答 2

2

Look at Fisher-Yates shuffle algorithm here for your requirement.

于 2012-07-13T07:35:16.957 回答
1

这是另一种方法:

  1. Create array of 10 elements and fill it with the values you want to randomize (0, 1, ..., 9).
  2. Iterate for k from 9 down to 0 and pick a random number index = rand(k).
  3. Swap the element at position k with the element at position index.

At the end your array will contain a random permutation of the original values, which is exactly what you wanted.

于 2012-07-13T07:34:32.547 回答