您的位置:首页 > 其它

随机生成一个连续数的序列

2012-02-22 15:48 218 查看
最近,在编写自己呃数独游戏过程中,遇到需要生成一些随机但连续的数字序列的需求。当时,为了尽快实现功能,临时写了一个凑合着用。

现在有时间,写一个通用的,生成随机但连续数的序列的函数,当然原理很简单。

// generate a random number list length of which is size;
// the range of numbers is 0 to size-1;
bool CreateRandomSequenceNumbers(int size, int* randomSequence)
{
if ( size <= 0 || (randomSequence == NULL))
{
return false;
}

srand(::GetTickCount() % 100);

struct RandomNumbers
{
int Value;
bool Selected;
};

// check status
RandomNumbers* tempValidList = new RandomNumbers[size];
for (int i=0; i<size; i++)
{

tempValidList[i].Value = i;
tempValidList[i].Selected = false;
}

int leftCount = size;
int validIndex = 0;
while(leftCount > 0)
{
int target = rand() % leftCount;
int flag = 0;
for (int i=0; i<size; i++)
{
if (tempValidList[i].Selected)
{
continue;
}
if (flag == target)
{
randomSequence[validIndex++] = tempValidList[i].Value;
tempValidList[i].Selected = true;
leftCount--;
break;
}
flag++;
}
}

delete[] tempValidList;
}


这段代码的逻辑是通过rand()方法,不断地生成随机数,从而生成一个不重复的随机序列,每找到一个合适的数字后,将该数字的Selected字段标记为true,这样,下次再找它的时候,就直接跳过。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: