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

后端 未结 3 1326
谎友^
谎友^ 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: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.

提交回复
热议问题