生成小于n且没有重复的k个整数可以使用如下方法:
方法一:使用C++的set,由于set具有排序功能,而且里面的数不会重复,所以可以生成随机数字插入到set中,直到set中的数字个数为k,具体代码如下:
//solution 1:use set #include<iostream> #include<set> #include<ctime> #include<cstdlib> using namespace std; #define N 10000000 int main() { set<int> S; set<int>::iterator j; int i; int k; cout<<"please input k:"<<endl; cin>>k; srand((unsigned)time(NULL)); //gererate k numbers by random and put them into S while(S.size() < k) { i = rand()%N; S.insert(i); } for(j=S.begin();j!=S.end();j++) cout<<*j<<" "; return 0; }
方法二:使用一个数组,按顺序存放n个数,然后把数组中到数字打乱,取前k个数字。代码如下
#include<cstdlib> #include<iostream> #include<ctime> using namespace std; #define N 10000000 void swap(int a,int b); int main() { int i; int k; int *num = new int[N]; cout<<"please input k:"; cin>>k; //initialized num array for(i = 0;i < N;i++) num[i] = i; //swap numbers of array srand((unsigned)time(NULL)); for(i = 0;i < k;i ++) swap(num[i],num[rand()%N]); //output numbers for(i = 0;i < k;i ++) cout<<num[i]<<" "; delete[] num; cout<<endl; } void swap(int a,int b) { int temp; temp = a; a = b; b = temp; }