4 winner lottery

How do i modify the following code so that a number isn't repeated more than once?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  #include<iostream>
#include<time.h>
#include<stdlib.h>
#define MAX_NUM 25
using namespace std;
void randnum()
{
	int random;
	srand(time(NULL));
	for (int i = 0; i<4; i++)
	{
		random = rand() % MAX_NUM;
		cout << random << endl;
	}
}
int main()
{
	cout << "The four winners are: " << endl;
	randnum();
	return 0;
}
Last edited on
int used[maxnum] = {0};

get a random number, check to see if used[number] == 0.
if it does, increment used[number] and print it.
if it does not, get another random number.
what would i be writing in code, specifically?

i'm very new to programming, so i only half-get what you're saying
1
2
3
4
5
6
7
8
9
10
int used[ MAX_NUM] = {0}; //zero is 'false'

for (int i = 0; i<4; i++)
	{
           do{
		   random = rand() % MAX_NUM;                   
               }while (used[random])  //if its true, its not zero, and you already saw this value
                 used[random] ++;
		cout << random << endl;         
	}


now you see it in code, but do you understand how it works?
you need a different technique if maxnum becomes huge, but this works for a LOT of small problems of this type. Note that if you wanted 24 of 25 values it could get into a loop for a *while* looking for that last available value, so use the technique when you are not trying to get most of the list.

style stuff...
#define constants are not as nice as
const int MAX_NUM = 25;
the macro ones can give trouble in some code due to implicit type

use <cstdio> <ctime> not the C versions, as the namespace added to the <c***> versions is important and can cause odd behavior in some larger programs.
Last edited on
Topic archived. No new replies allowed.