考虑给定一个特定范围(0 到 5,000,000),我应该从该范围生成 2,500,000 个唯一随机数。什么是有效的方法来做到这一点?我知道很难获得真正的随机数。
我尝试检查一个数字是否存在,以便生成一个新的随机数。但是计算需要几个小时。有一个更好的方法吗。
这背后的原因是,我有一个大小为 5,000,000 的向量。我想将矢量缩小一半。即从向量中随机删除 50% 的元素。
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <algorithm>
using namespace std;
#define NUMBER 2500000
#define RAND_START 0
#define RAND_END 5000000
unsigned int generate_random_number(int min, int max)
{
return min + (rand() % (unsigned int)(max - min + 1));
}
int main(int argc, char* argv[])
{
unsigned int count = 0, random_number;
vector<unsigned int> rand_vector;
do
{
count++;
random_number = generate_random_number(RAND_START,RAND_END);
// Tried to manually add a different number each time. But still not a considerable improvement in performance.
if (std::find(rand_vector.begin(), rand_vector.end(), random_number) != rand_vector.end())
{
if(random_number > count)
random_number = random_number - count;
else
random_number = random_number + count;
}
rand_vector.push_back(random_number);
sort(rand_vector.begin(), rand_vector.end());
rand_vector.erase(unique (rand_vector.begin(), rand_vector.end()), rand_vector.end());
}while (rand_vector.size() != NUMBER);
for (unsigned int i =0; i < rand_vector.size(); i++)
{
cout<<rand_vector.at(i)<<", ";
}
cout<<endl;
return 0;
}
我可以通过什么更好的方法来做到这一点?