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


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

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

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

  • 相关阅读:
    编程模式
    iOS----FMDB---看这个可以解决大部分你遇到的问题
    iOS UITableView的使用
    ios文件系统文件目录操作
    Core Data-备用
    数组去重复
    用法总结:NSArray,NSSet,NSDictionary-备用
    iOS 摇一摇的实现
    更改xcode上iphone模拟器颜色的方法--备用
    模式识别之基础---mqdf分类器==MQDF改进的二次分类器
  • 原文地址:https://www.cnblogs.com/quark/p/2363270.html
Copyright © 2020-2023  润新知