编程珠玑: 12章 取样问题 12.1程序的输入包含两个整数m和n,其中m

#include 
#include 
#include 
#include 

using namespace std;
/*
问题:程序的输入包含两个整数m和n,其中m max)
	{
		int temp = min;
		min = max;
		max = temp;
	}
	return ( rand() % (max - min + 1) + min );
}

//生成0~n-1中m个随机选择的不重复的数组成的有序列表
vector getRandomVector(int m , int n)
{
	vector results;
	for(int i = 0 ; i < n ; i++)
	{
		//从剩余n-i个数中选择m个数的概率为 m/(n-i)
		int randValue = rand();
		if( randValue % (n-i) < m )
		{
			//选中当前数,就使得剩余带选择个数减少
			m--;
			results.push_back(i);
		}
	}
	return results;
}


void print(vector& results)
{
	if(results.empty())
	{
		cout << "no result" << endl;
		return;
	}
	int size = results.size();
	for(int i = 0 ; i < size; i++)
	{
		cout << results.at(i) << " ";
	}
	cout << endl;
}

void process()
{
	int m , n;
	vector results;
	while(cin >> m >> n)
	{
		results = getRandomVector(m , n);
		print(results);
	}
}

int main(int argc , char* argv[])
{
	process();
	getchar();
	return 0;
}

你可能感兴趣的:(编程珠玑)