Consider I am given a specific range (0 to 5,000,000) and I should generate 2,500,000 unique random numbers from this range. What is an efficient way to do this? I understand that is tough to get true random numbers.
I tried by checking if a number exists so that I can generate a new random number. But it takes hours to compute. Is there a better way to do this.
The reason behind this is, I have a vector of size 5,000,000. I want to shrink the vector exactly by half. i.e. delete random 50% of the elements from the vector.
#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;
}
Any better approach by which I can do this?