Reputation: 51
this is my first question here, i'm making a little game, and for assigning the roles, i need random numbers. I have this code, but is possible that the numbers don't be repeated? Thanks.
void giveroles() {
srand(time(NULL));
int r = rand() % i + 1;
switch ( r ) { /* ... */ }
}
Upvotes: 1
Views: 152
Reputation: 16582
If you want to randomly assign a small set of numbers, rather than generate them at random, create a list of the numbers you want, and then randomise the order of the list (iterate over the list, randomly swapping entries).
For example:
int cards[52];
for(int i = 0 ; i < 52 ; i++)
{
cards[i] = i;
}
for(int i = 0 ; i < 1000 ; i++)
{
int r1 = rand()%52;
int r2 = rand()%52;
int t = cards[r1];
cards[r1] = cards[r2];
cards[r2] = t;
}
for(int i = 0 ; i < 52 ; i++)
{
printf("%d\n", cards[i]);
}
For completeness, it has been pointed out that shuffling in this fashion is biased. Here's a variation which should be unbiased:
cards[0] = 0;
for(int i = 1 ; i < 52 ; i++)
{
int r = rand() % (i+1);
cards[i] = cards[r];
cards[r] = i;
}
(it should be further noted that taking the module of rand() is also likely to be biased, as the range of rand() will not be an even multiple)
Upvotes: 4
Reputation: 129314
If you don't want to repeat random numbers, the solution is to keep track of which random numbers you have previously used, and if you get a "hit" in your list of existing numbers, try again.
Also, using srand(time(NULL));
should only be done once. I suspect this is more the question you were actually asking.
Upvotes: 3
Reputation: 212929
Take out the line srand(time(NULL));
. You should in general only ever do this once in your program, e.g. at the start of main()
, in order to randomize the seed used by subsequent calls to rand()
.
Upvotes: 3