quark

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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

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

// 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,这样,下次再找它的时候,就直接跳过。

posted on 2012-02-22 15:48  QuarkZ  阅读(543)  评论(0编辑  收藏  举报