generate 5 unique random numbers in an array.

Another question. This one is about loops and arrays in a function.
I have to generate 5 unique lottery numbers in the range of 1 to 50 inclusive.

This is what I have:
1
2
3
4
5
6
7
8
9
void generateLotteryNumbers(int lotteryNumbers [])
{
    int index = 0;
    for (int counter = 0; counter < 5; counter++)
    {
            lotteryNumbers[index] = rand()%50 + 1;
            index++;
    }
}


It generates my 5 lottery numbers just fine, however, run it a few times, and eventually you get two numbers that are the same.
I tried doing a really complicated for - do - while loop that said for 5 iterations do generate random lottery numbers, while the newest one is == to the last one generate a new number , but it didn't work, then I tried a do - while loop that was kind of similar. I even just tried a for loop with an if statement, which worked, but would give me a very small statistical probability of generating the same number twice, and I think part of the point of this exercise is validation to make sure they are all unique.
Any help is appreciated.
One idea is to create a set and keep adding to it until the size of the set is the desired size.

Sets do not maintain duplicates and will prevent your list from ever being doubled up.
1
2
3
4
5
6
void generateLotteryNumbers( set<int> *ln ){
	while( ln->size() < 5 ){
		ln->insert( rand()%50+1 );
		cout << "\nWORKING\n";
	}
}


However, if you want to go the route of using an array, I recommend the option of doing the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void generateLotteryNumbers(int lotteryNumbers [])
{
    int index = 0;
	int new_num;
    for (int counter = 0; counter < 5; counter++)
    {	
		do{
			new_num = rand()%50 + 1;
			for( int i = 0; i < 5; i++ ){
				if( new_num == lotteryNumbers[i] ){
					new_num = 0;
					break;
				}
			}
		}while( new_num == 0 );
            lotteryNumbers[index] = new_num;
            index++;
    }
}
I have to use an array, and yup, that did it. You are awesome.
Topic archived. No new replies allowed.