蓄水池采样算法
一般的问题是从n个数中随机取k个数字,采用的是蓄水池采样算法
k是1的情况:
代码如下所示:
int shiyan_suijishu()
{
int a[] = { 0,1,2,3,4,5,6,7,8,9 };
int xunshuicchi = a[0];
for (int i = 1; i < 10; ++i)
{
int rand_n = rand() %(i+1) ;
if (rand_n < 1)
xunshuicchi = a[i];
}
return xunshuicchi;
}
k不是1的情况:
int shiyan_suijishu_k()
{
vector<int> temp(10, 0);
for (int jj = 0; jj <= 10000; ++jj)
{
int a[] = { 0,1,2,3,4,5,6,7,8,9 };
//int xunshuicchi = a[0];
int b[2];
b[0] = a[0];
b[1] = a[1];
//二级蓄水池
for (int i = 2; i < 10; ++i)
{
int rand_n = rand() % (i + 1);
if (rand_n < 2)
b[rand_n] = a[i];
}
++temp[b[0]];
++temp[b[1]];
//cout << " -----------------------------" << endl;
}
for (auto r : temp)
cout << r << endl;
return 1;
}