Shuffle elements of an array/n numbers uniformly randomly. Possibley in expected O(n) time

后端 未结 3 1323
谎友^
谎友^ 2021-01-06 17:47

Is it possible to shuffle elements of an n-sized array uniformly, i.e. the probability of any of the n! combinations occurring is the same, in expected O(n) tim

相关标签:
3条回答
  • 2021-01-06 18:29

    What you want is random sample of set, that samples each element with equal probability.

    0 讨论(0)
  • 2021-01-06 18:40

    For each array position:

    Select a random number from current position to end of array

    Swap current position with random position

    That should give you O(n) without the challenge of finding an unused array position. This assumes you can use an in-place swap and that you don't have to create a new array.

    0 讨论(0)
  • 2021-01-06 18:45

    You should look at the Fisher-Yates shuffle.

    From the article:

    Properly implemented, the Fisher–Yates shuffle is unbiased, so that every permutation is equally likely. The modern version of the algorithm is also rather efficient, requiring only time proportional to the number of items being shuffled and no additional storage space.

    So it meets your requirements. It's pretty easy to implement too.

    0 讨论(0)
提交回复
热议问题