总是碰到如题的问题,也许是现实世界有太多随机事件了吧。
首先取集合中一个单位作为新随机队列的初始值,然后将其余单位随机放入指定位置,当发现指定位置不为初始值时向后退一位(最后边界时回到首部)。
以下均为c#代码
下面是大饼排序问题中集合随机排序的应用片段,用于生成随机烙饼队列
void init()
{
//初始化赋值
cakeArray = new int[cakeNum];
cakeSizeArray = new int[cakeNum];
for (int i = 0; i < cakeSizeArray.Length; i++)
{
cakeSizeArray[i] = i;
}//大饼直径初始化
}
void randomCollection()
{
if (cakeSizeArray.Length != cakeArray.Length)
return;
Random r = new Random();
for (int i = 0; i < cakeSizeArray.Length; i++)
{
cakeArray[i] = cakeSizeArray[0];
}
for (int i = 1; i < cakeSizeArray.Length; i++)
{
int address = r.Next(10);
for(;;)
{
if (address > cakeSizeArray.Length)
address = 0;
if (cakeArray[address] != cakeSizeArray[0])
address++;
else
break;
}
cakeArray[address] = cakeSizeArray[i];
}
//打印结果
for (int i = 0; i < cakeSizeArray.Length; i++)
{
Console.Write("{0}\t", cakeSizeArray[i]);
}
Console.WriteLine();
for (int i = 0; i < cakeArray.Length; i++)
{
Console.Write("{0}\t", cakeArray[i]);
}
Console.ReadLine();
}
以下是穷举n个烙饼排列
void enumeratQueue(int cn)//cn为烙饼数
{
if (cn == 1)
{
int t = cakes.Dequeue();
cakeArray[0] = t;
setMaxTime();//重置maxTime
search(0);
minTime = maxTime > minTime ? maxTime : minTime;
show();
cakes.Enqueue(t);
}
for (int i = 0; i < cn; i++)
{
int t = cakes.Dequeue();
cakeArray[cn - 1] = t;
enumeratQueue(cn - 1);
cakes.Enqueue(t);
}
}
本文转自today4king博客园博客,原文链接:http://www.cnblogs.com/jinzhao/archive/2008/08/20/1272442.html,如需转载请自行联系原作者