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

十年热恋 提交于 2019-12-09 01:04:18

问题


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) time. How so? I have to shuffle elements of A to a new array B The first thing that comes to my mind when I'm trying to do this is just picking a random number i from 1 to n, see if A[i] has already been picked, if so, then repeat, otherwise put A[i] in the first available position in B. However, this coupon collector problem has expected time O(n log n). Can someone suggest an O(n) expected time algorithm.

Thanks.


回答1:


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.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/5613886/shuffle-elements-of-an-array-n-numbers-uniformly-randomly-possibley-in-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!