srand(time(NULL));
for(i=0;i<9;i++)
{
random: temp=rand()%9;
for(j=0;j<=i;j++)
{
if(temp==randarr[j])
{
goto random;
}
}
randarr[i]=temp;
// printf("%d ",randarr[i]);
}
I want to generate random numbers between 0 to 8 without repeat any number. I use this code it works perfectly. But I want to remove goto statement from my code. how can i write my code without goto? Thanks!!
You don't want to generate every number randomly. You want to shuffle the numbers from 0 to 8 in some random order.
A far simpler approach (that also eliminates the use of goto) is to start from a sorted array and pick an index to swap with randomly each iteration.
srand(time(NULL));
int randarr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
for(int i = 0; i < 9; ++i)
{
int swap_idx = rand() % 9;
int temp = randarr[swap_idx];
randarr[swap_idx] = randarr[i];
randarr[i] = temp;
}
As noted by HolyBlackCat, the naive approach tends to give a non-uniform distribution of the various permutations. If that is a concern for you, an improvement is possible in the form of the Fisher-Yates (or Knuth) shuffle
srand(time(NULL));
int randarr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
for(int i = 0; i < 9; ++i)
{
int swap_idx = i + rand() % (9 - i);
int temp = randarr[swap_idx];
randarr[swap_idx] = randarr[i];
randarr[i] = temp;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With