n个数随机抽取m个

0到n-1中随机输出m个数

// l0.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <time.h>
#include<cstdlib>
#include<iostream>

using namespace std;
//<1>rand()函数 C++建议使用#include<cstdlib>
//<2>rand()可以生成0~RAND_MAX之间的一个随机数,其中RAND_MAX 是stdlib.h 中定义的一个整数,它与系统有关。
void m_from_n(int n, int m)
{ 
    srand((unsigned int)time(0)); 
    for (int i = 0; i < n; i++) { 
        if (rand()%(n-i)<m) {//《3》 保证输出概率为m/n
			/*
				n个数排队来抽签!
				《3.1》每个数抽签后,剩余名额和剩余的数都是变化的。
				第二个数中签概率:
					m/n * (m-1)/(n-1) + (n-m)/n * m/(n-1)=m/n
				其实排队抽签法就是"从n个数中选m个不同数",抽签过程中概率是变化的,但其概率抽签前都是m/n.
			*/
            cout << i << endl;//《2》保证输出不重复的数
			m--;//《1》保证输出m个数
        }
     }
}

int main(int argc, char* argv[])
{
	m_from_n(30,3);
	system("pause");
	return 0;
}


猜你喜欢

转载自blog.csdn.net/xiziyunqi/article/details/82813334