0

I am trying to generate a random number, but it should not be a particular number. So i am passing the number which should not be the random number and the range in which it has to be generated to the function, and i am reinvoking the function if the random number generated is the number, which should not be generated, so this is taking a long time and resulting in termination of my program. I am using the following code, let me know how effecient i can generate the random number without waiting for long or even without reinvoking the function.

here rank1 is the number passed to it, which should not be generated and size1 is the number, denoting the range of the maximum accepted value

int rgenerator(int rank1, int size1)

{

int iseed, k;
time_t seconds;
time(&seconds); 
iseed=(unsigned int) seconds;


srand(iseed);



k=rand()%size1;

if(k!=rank1)
return k;
else 
rgenerator(rank1,size1);

}
4
Contributors
3
Replies
5
Views
5 Years
Discussion Span
Last Post by cluekiller
0

1) Never call srand() where you need a random number. Call it once at the beginning of the program only.
2) use a while loop instead of a recursive function.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.