您的位置:首页 > 编程语言 > C语言/C++

C/C++产生[m, n)之间不重复的随机序

2014-02-22 11:16 225 查看
/*
*Rand a Sequence
*Author:p.j.gan
*Date:2014/2/22
*Complier:vs2010
*/

/*
*Param:
*iMax: the rande data
*iLen: the length of the Buffer
*pSequenceBuffer: Buffer
*/
void randSequence(int iMin, int iMax, int iLen, void *pSequenceBuffer) {
	assert(pSequenceBuffer);
	int *pn1=new int[iLen+1];
    int *pn2=new int[iLen];
	int i,tmp;
	srand((unsigned)time(NULL));
	std::memset(pn1, 0, sizeof(int) * (iLen + 1));
	for(i=0;i < iLen;i++)
	{
		tmp=rand() % iMax + iMin;
		if(pn1[tmp]==0) {
			pn2[i]=tmp;
			pn1[tmp] = -1;
		}else {
			--i;
		}
	}
	std::memcpy(pSequenceBuffer, pn2, sizeof(int) * iLen);
	for(int i = 0; i < iLen; i++) {
		std::cout<<*((int *)pSequenceBuffer + i)<<" ";
	}
	std::cout<<std::endl;

	// destory the memory
	if(pn1 != 0) {
		delete []pn1;
		pn1 = 0;
	}
	if(pn2 != 0) {
		delete []pn2;
		pn1 = 0;
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐