Reputation: 1245
I want to make a random number generator where the user specifies the range and amount of generated numbers. I want it to make every number unique (no repeat). This is what I've done so far (it generates but some of them repeat, why?)
#include <time.h>
#include <stdio.h>
#include <windows.h>
#include <conio.h>
int main()
{
srand(time(NULL));
int start, stop, amount;
system("chcp 1250 >nul");
printf("Welcome to random number generator!\n");
printf("\nWhat range? \nFrom: "); scanf("%i", &start);
printf("To: "); scanf("%i", &stop);
printf("\nHow many numbers?: "); scanf("%i", &amount);
int number[amount];
for(int i=0; i<amount; i++)
{
number[i] = rand() % ((stop+1)-start) + start;
for(int j=i; j>-1; j--)
{
if(number[i]==number[j])
{
number[i] = rand() % ((stop+1)-start) + start;
}
}
printf("\n%i generated number: %i", i+1, number[i]);
Sleep(10);
}
getch();
}
Upvotes: 0
Views: 397
Reputation: 642
So, even if we assume that rand() is a perfect random number generator, the numbers would repeat. Lets say you have to generate 100 numbers. Say your start = 1 and stop = 100.
you generate a first number from 1 to 100, then the second and so on.. The more numbers you've used so far, the easier it is to get a duplicate.
Then you find a duplicate with that inner for-loop. You generate a new number for number[i], but you have no guarantee that this number's unique. You may as well end up setting number[i] to another duplicate.
If you want your code to work, you have to keep changing number[i] as long as it has a duplicate.
That's regarding the bug in your code. On the other hand, this code is horribly inefficient, so you should consider optimising it if you plan on running this procedure often.
Upvotes: 0
Reputation: 360902
Your "check for dupes" loop is incorrect. You might find a duplicate, but then you don't check if that re-generated number exists in the stuff you ALREADY tested.
e.g. consider an array like this. user asked for 5 numbers, range 1-10
number[0] = 5
number[1] = 6
number[2] = 2
number[3] = 8
Now you're working on number[4]. You generate 2
... You scan the array backwards and find that 2
is a dupe. So you generate a new number... and generate 8
. But you don't reset your j
loop - you just keep working backwards, and never see that 8
was already in the array.
What you should have is something more like:
for(int j=i; j>-1; j--) {
if(number[i]==number[j]) {
number[i] = rand() % ((stop+1)-start) + start;
j = i; // RESET THE LOOP
}
}
And note that your code can easily produce an infinite loop. e.g. consider someone asking for numbers in a range 1-3, and generate 4 of them. 1,2,3,?
. The condition can never be satisfied, because you can't have 1-3 without at least one repeat.
Upvotes: 3