Shuffling is a procedure used to randomize a deck of playing cards to provide an element of chance in card games.
Shuffling的目标是要Shuffling后所有可能情况的概率一样。
Before:
After:
这里介绍两种简单的shuffling算法:
1)Sort shuf?e :
?Generate a random real number for each array entry.
?Sort the array.
2)Knuth shuffle:
?In iteration i, pick integer r between 0 and i uniformly at random.
?Swap a[i] and a[r].
public class Knuth
{
public static void shuffle(Object[] a)
{
int N = a.length;
for (int i = 0; i < N; i++)
{
int r = StdRandom.uniform(i + 1);
exch(a, i, r);
}
}
}
如果,这里不是在[0,i]间产生r,而是在[0,N-1]产生r,将会产生Broken Knuth shuf?e,其每种情况将不是等概率的。
原文地址:http://blog.csdn.net/kzq_qmi/article/details/46446591