很多算法题目需要大量数据作为原始数据测试算法的性能,自己写了一个生成指定范围内指定个数的不重复随机数的生成函数。下面是代码,有错误请指正。
#include<time.h> #include<iostream> #include<bitset> using namespace std; #define NUMS 1000000 #define NMIN 0 #define NMAX 10000000 int * creatArrWithoutD(int,int,int); int * creatArrWithD(int,int,int); int existDuplicate(int *arrInt,int num); int main() { int num=NUMS; int nmin=NMIN; int nmax=NMAX; if(nmax<nmin) return -1; /*生成数组*/ int *arr = creatArrWithD(num,nmin,nmax); for (int i=0; i<num; i++) { cout<<arr[i]<<" "; } cout<<endl<<"----生成完成----"<<endl; /*测试重复性*/ int dn=existDuplicate(arr,num); if(dn>=0) cout<<"存在重复数字: "<<dn; else cout<<"不存在重复数字"; cout<<endl; /*扫尾工作*/ delete [] arr; return 0; } //判断是否存在重复数字 //不存在返回-1 //存在返回第一个重复数字 int existDuplicate(int *arrInt,int num){ bitset<NMAX-NMIN+1> *b=new bitset<NMAX-NMIN+1>(0); for (int i=0; i<num; i++) { int index=arrInt[i]; //cout<<index<<endl; if(!(b->test(index-NMIN))) b->set(index-NMIN); else return index; } delete [] b; return -1; } //生成num个[nmin,nmax]范围内的不重复随机数 int * creatArrWithoutD(int num,int nmin,int nmax){ if(num>(nmax-nmin+1)) return NULL; int area=nmax-nmin+1; int *arrange = new int [area]; int *nums = new int [num]; int index; for (int i=0; i<area; i++) arrange[i] = i+nmin; for (int i=0; i<num; i++) nums[i] = i; srand((int)time(0)); for (int i=0; i<num; i++) { index = (int)((float)(area-i) * rand() / (RAND_MAX+1.0)); nums[i]=arrange[index]; //cout<<arrange[index]<<endl; arrange[index] = arrange[area-1-i]; } delete [] arrange; return nums; } //生成num个[nmin,nmax]范围内的重复随机数 int * creatArrWithD(int num,int nmin,int nmax){ int area=nmax-nmin+1; int *arrange = new int [area]; int *nums = new int [num]; int index; for (int i=0; i<area; i++) arrange[i] = i+nmin; for (int i=0; i<num; i++) nums[i] = i; srand((int)time(0)); for (int i=0; i<num; i++) { index = (int)((float)(area) * rand() / (RAND_MAX+1.0)); nums[i]=arrange[index]; //cout<<arrange[index]<<endl; //arrange[index] = arrange[area-1-i]; } delete [] arrange; return nums; }