閱讀668 返回首頁    go 阿裏雲 go 技術社區[雲棲]


編程珠璣之1.4生成小於n且沒有重複的k個整數

生成小於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;
}


       

最後更新:2017-04-04 07:03:32

  上一篇:go POJ 2234 尼姆博奕
  下一篇:go hibernate之映射關係多對多