问题定义:从n个数中,等概率的抽取m个数。
真心觉得自己概率论学得不咋第。第一个和第三个函数还是没有看懂。
#include <iostream>
#include <algorithm>
#include <set>
#include <stdlib.h>
using namespace std;
void genknuth( int m, int n)
{
srand(5);
for( int i = 0; i < n; i++)
if( (rand() % (n - i) < m))
{
cout << i << "\n";
m--;
}
}
void gensets( int m, int n)
{
set<int> s;
while( s.size() < m)
s.insert( rand() % n);
set<int>::iterator i;
for( i = s.begin(); i != s.end(); i++)
cout << *i << endl;
}
/* 习题9: 当m接近n时,基于集合的算法会产生很多集合中早就存在的整数,因此需要去掉这些整数。写出一个算法,即便在最坏情况下,该算法也只需要m个随机数值?
*/
void genfloyd( int m, int n)
{
set<int> s;
set<int>::iterator i;
for(int j = n - m; j < n; j++)
{
int t = rand() % ( j + 1);
if( s.find(t) == s.end())
s.insert(t);
else
s.insert(j);
}
for( i = s.begin(); i != s.end(); i++)
cout << *i << "\n";
}
void getshuf( int m, int n)
{
int i, j;
int *x = new int[n];
for( i = 0; i < n; i++)
x[i] = i;
for( i = 0; i < m; i++)
{
j = (rand() %( n - 1- i)) + i;
int temp = x[i]; x[i] = x[j]; x[j] = temp;
}
sort( x, x+m);
for( i = 0; i < m; i++)
cout << x[i] << "\n";
}
int main(int argc, char* argv[])
{
cout << "genknuth: " << endl;
genknuth( 5, 10);
cout << "gensets:" << endl;
gensets( 5, 10);
cout << "getshuf:" << endl;
getshuf( 5, 10);
}
本文介绍了一种从n个数中等概率抽取m个数的方法,包括Knuth算法、基于集合的算法、Floyd算法和洗牌算法。这些算法在不同场景下各有优劣。
789

被折叠的 条评论
为什么被折叠?



