I sometimes get the same random numbers with the code below. How can I fix this?
int main()
{
int numbers[6];
srand(time(0));
for(int j=1;j<=6;j++)
{
numbers[j]=rand()%10;
printf("\n%d",numbers[j]);
}
}
I sometimes get the same random numbers with the code below. How can I fix this?
int main()
{
int numbers[6];
srand(time(0));
for(int j=1;j<=6;j++)
{
numbers[j]=rand()%10;
printf("\n%d",numbers[j]);
}
}
The main issue is that your range is kind of small, so duplicates, while they aren't necessarily common, they'll crop up enough to annoy you.
I've got two suggestions, the first being to increase the range of your random numbers
int main(void) {
int nums[6];
srand(time(NULL));
for (int i = 0; i < 6; ++i) {
nums[i] = rand() % 100; // range has been increased
printf("%d\n", nums[i]);
}
}
Another way to absolutely ensure unique numbers would be to check if your array already contains the number before adding it. As you might guess, depending on the way you implement it, time complexity will become a factor.
int main(void) {
int nums[6];
srand(time(NULL));
for (int i = 0; i < 6; ++i) {
int temp = rand() % 10;
bool exists = false;
for (int j = 0; j < i; ++j) {
if (nums[j] == temp) {
exists = true;
break;
}
}
if (!exists) {
nums[i] = temp;
printf("%d\n", nums[i]);
}
else {
--i; // force the loop back
}
}
}