-1

I am trying to generate two different random numbers in C within a given range.The range is

0 to nk-1

But my following code sometimes works and sometimes fails.What is the reason behind this?

n1=rand()%nk;
n2=rand()%nk;
while(n1==n2)
{
 srand(time(0));
 n2=rand()%nk;
} 
Sumeet
  • 8,086
  • 3
  • 25
  • 45
  • 4
    `srand()` should be called only once to seed the random generator. Do not call it inside the while loop ! – francis Sep 20 '15 at 17:55
  • 1
    The canonical duplicate is: [`srand()`: why call it only once?](http://stackoverflow.com/questions/7343833/srand-why-call-it-only-once/). – Jonathan Leffler Sep 20 '15 at 17:57
  • If you like to generate two different random numbers in that range you should use n1 = rand()%nk; n2 = rand()%(nk-1); if(n1 == n2) n2 += 1; You should avoid the while loop. – Christian Fries Sep 20 '15 at 18:04
  • I don't see that this is a duplicate (given that he states in a comment, that he get's a segmentation fault). He should clarify what "fails" means. – Christian Fries Sep 20 '15 at 18:43

2 Answers2

3

You're supposed to seed the RNG once,

srand(time(0));
n1=rand()%nk;
n2=rand()%nk;
while(n1==n2)
{
 n2=rand()%nk;
}
Aldehir
  • 2,025
  • 13
  • 10
  • Cool,now its working.Can you please throw some light on the reason.Explanation would be great. – Sumeet Sep 20 '15 at 17:58
  • Take a look at the answer for [this question](http://stackoverflow.com/questions/5574914/srandtimenull-doesnt-change-seed-value-quick-enough). – Aldehir Sep 20 '15 at 18:00
  • I am sorry ,I only ran it 4 to 5 times. But when I ran it for 12 th time still segmentation fault. I don't think it correct. – Sumeet Sep 20 '15 at 18:04
  • @Dante. The segmentation fault is occurring somewhere else. I suggest you run it through a debugger to determine the cause. – Aldehir Sep 20 '15 at 18:20
1
srand(time(0));  

This has to be outside loop.

In loop you reseed the RNG , whereas you should be doing it once.

ameyCU
  • 16,489
  • 2
  • 26
  • 41