### Generating unique numbers.

Hello masters. I'm new to programming and we have this school project that we need to create a lotto game.

 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344`` `````` #include "iostream" #include #include using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int lotto[5], y; int num[5],x; srand (time(NULL)); for (x=0;x<5;x++) { cout<<"Input your lotto number "<<"(0-9 ): "; cin>>num[x]; while (num[x]<0 || num[x]>9) { cout<<"Error! Please input your lotto number: "<<"(0-9)"<>num[x]; } } for (y=0;y<5;y++){ lotto[y] = (rand()%10); cout<<" "<

So far this is my code, yes it's not polished and I hope you give advice on what I should edit,etc.

My question is: How can you output 5 unique numbers? Since 4/10 tries, there are 2-3 same numbers. All should be unique.
Random numbers are not guranteed to be unique. A simple way would be to keep generating random numbers until a number is generated that is not present in the existing array.
closed account (S6k9GNh0)
http://en.wikipedia.org/wiki/Universally_unique_identifier

EDIT: Also, http://en.wikipedia.org/wiki/Globally_unique_identifier
Last edited on

Here is a method that you should be able to follow
 ``12345678910111213141516171819202122232425262728293031323334353637`` ``````#include #include #include int main () { srand (unsigned (time(NULL))); int lotto_numbers[10] = {0,1,2,3,4,5,6,7,8,9}; int draw[5]= {-1,-1,-1,-1,-1}; // make the lotto draw for(int index =0; index < 5; index++) { int ball = -1; do { int pick = (rand() % 10); ball = lotto_numbers[pick]; lotto_numbers[pick] = -1; }while(ball == -1); draw[index] = ball; } // Display the lotto draw std::cout << "The Lotto draw:"; for(int index =0; index < 5; index++) { std::cout << draw[index] << " "; } std::cout << std::endl; return 0; }``````
One way would be to make an array out of a set of numbers. Then shuffle the array, and then pick the first 5.
Hmmm....well, numbers should not be repeated (both lotto and input numbers). I don't know how to validate numbers so it would give an error if I input the same number twice.

I think I'm good with the srand function since it's working fine. Next problem is how to validate the numbers so it won't repeat itself for the lotto numbers and for the user input, it should give an error if you input a number twice.
` I don't know how to validate numbers so it would give an error if I input the same number twice. `

Take a look at line 21.

 ``123456789101112131415161718192021222324252627`` ``````#include #include #include using namespace std; int main () { int randNum; vector lotto; for(int i = 0; i < 10; ++i) lotto.push_back(i); srand (time(NULL) + rand()); for(int i = 0; i < 5; ++i) { randNum = rand() % (10 - i); cout << lotto[randNum] << " "; lotto.erase(lotto.begin() + randNum); } cout << '\n'; system ("pause"); return 0; }``````
Last edited on
Topic archived. No new replies allowed.