Hi all, I want to generate any random integer from 1 million to 30 million, so here is the code I've written.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
usingnamespace std;
int digit[7];
longint id=0;
int main()
{
srand(time(NULL));
for (int n=1; n<100000; n++)
{
digit[6]=rand()%29+1; //1,XXX,XXX to 30,XXX,XXX
for (int i=5; i>=0; i--) {digit[i]=rand()%10+1;} //Other digits
id=digit[6]*pow(10,6)+digit[5]*pow(10,5)+digit[4]*pow(10,4)+digit[3]*pow(10,3)+digit[2]*pow(10,2)+digit[1]*10+digit[0]; //Summation
cout << id << "\n";
}
return 0;
}
It works seemingly good. However if I want all the numbers to be unique, do I have to store all results in a list (array), then check if any new integer generated is the same as any on the list, and discard it if it is? I need to generate a large quantity of numbers, say tens of thousands. Is there any better way?
You create multiple numbers in ranges [1..30] and [1..10] in order to create one number in range [1'000'000..30'000'000].
(Except that you don't allow any 0 within the XXX'XXX. Furthermore, the first numbers could be 30 and 10, which makes 31 million and change.)
However, you do have an additional requirement: unique values.
Think of a new deck of cards. Every card is unique, but they are neatly ordered.
What do the dealers do first? They shuffle the deck.
The cards are still unique, but in random order.