为什么以下code不产生随机排列? [英] Why does the following code NOT generate permutations randomly?
问题描述
可能重复:
<一href="http://stackoverflow.com/questions/5131341/what-distribution-do-you-get-from-this-broken-random-shuffle">What分配你从这个破碎的随机洗牌得到什么呢?
这是从Skiena的算法设计手册。
This is from Skiena's Algorithm Design Manual.
假定myrand(A,B)产生之间的随机数a和b的包容性。
Assume that myrand(a, b) generates a random number between a and b inclusive.
下面code产生均匀排列,随机
The following code generates permutations uniformly at random
for(int i = 0; i < n; i++)
swap( a[i], a[myrand(i, n-1)]);
而以下则没有。
whereas the following doesn't.
for(int i = 0; i < n; i++)
swap( a[i], a[myrand(0, n-1)]);
现在的问题是,为什么?
The question is, why?
推荐答案
在第一种情况下有恰好n!为执行该功能的可能路径(第一兰特有n的可能性,第二有n-1,...)。由于每个n个!可能的排列correspojnds到这些正好一个,它们被均匀地分布。
In the first case there are exactly n! possible paths for execution of the function (first rand has n possibilities, the second has n-1 ...). Since each of the n! possible permutations correspojnds to exactly one of these, they are uniformly distributed.
在第二种情况下,有n个分布^ n个可能的路径(n个可能chioces首次秒中,n ...)。这确实的没有的映射均匀的排列使分布是不均匀的。
In the second case, there are n^n possible paths of distribution (n possible chioces the first time, n the second...). This does not map uniformly to the permutations so the distribution is uneven.
要检查出来手动,生成所有可能性小N,就像3
To check it out "by hand", generate all possibilities for a small n, like 3
numbers chosen generated permutation
(0,0,0) (2,0,1)
... ...
这篇关于为什么以下code不产生随机排列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!