我们先看一下纸牌游戏。一幅纸牌由 52 张不同的纸牌组成,发牌时必须产生不重复的纸牌,而且洗牌过程必须公平,即 52! 中纸牌顺序应该等概率出现。很明显这种随机排列所产生的随机数必须均匀分布且独立。由此代码如下:
view plaincopy to clipboardprint?
using System;
using System.Diagnostics;
namespace Lucifer.CSharp.Sample
{
class Program
{
static void Main(string[] args)
{
//初始化牌局
int[] array = new int[52];
for (int i = 0; i <>(array);
//验证牌局
for (int i = 0; i < value =" array[i];" j =" 0;" j ="="">(T[] array)
{
Random random = new Random();
for (int i = 1; i <>(array, i, random.Next(0, i));
}
}
static void Swap
{
T temp = array[indexA];
array[indexA] = array[indexB];
array[indexB] = temp;
}
}
}
using System;
using System.Diagnostics;
namespace Lucifer.CSharp.Sample
{
class Program
{
static void Main(string[] args)
{
//初始化牌局
int[] array = new int[52];
for (int i = 0; i <>(array);
//验证牌局
for (int i = 0; i < value =" array[i];" j =" 0;" j ="="">(T[] array)
{
Random random = new Random();
for (int i = 1; i <>(array, i, random.Next(0, i));
}
}
static void Swap
{
T temp = array[indexA];
array[indexA] = array[indexB];
array[indexB] = temp;
}
}
}
代码示例中的 Permute
然而,我们要问的是 Permute
若根据该算法,答案为是。因为一共有 N! 种可能的排列,而 Swap
题外话:博主在实际代码运行中,发现上述代码能很好的完成洗牌算法要求,但不保证其能在商业化项目中得以正确实践。我记得云风兄在他的博客上也曾经讨论过洗牌算法,有兴趣的兄弟可以搜索一番。
转自:http://www.cnblogs.com/lucifer1982/archive/2009/03/05/1404106.html
0 评论:
发表评论