Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   C (http://www.programmingforums.org/forum60.html)
-   -   non-repetitive random number (http://www.programmingforums.org/showthread.php?t=12570)

malms Feb 14th, 2007 2:30 AM

non-repetitive random number
 
hi guys,
when i generate k random numbers in range from 1 to 100, usually i got a few numbers that repeat themselves.
how can i generate the k non-repetitive random number?
i tried to do error checking, whether the new generated random number is the same with the old one, but it's not working

thanks

Jimbo Feb 14th, 2007 5:00 AM

Aside from using a method which will incur some overhead, you can't. And if it's random, you should allow for the possibility of having a duplicate. You could keep a list of previous numbers and check for a duplicate if you wanted to. Or, you could keep a pool of valid numbers, shuffle it up, and remove randomly indexed values from the shuffled list.

InfoGeek Feb 14th, 2007 8:54 AM

or you can do something like...
:

  for(i=0;i<100;++i)
    a[i] = i+1;

  for(i=0;i<100;++i)
    swap(a[i], a[rand()%100]);


kruptof Feb 14th, 2007 10:52 AM

Quote:

Originally Posted by InfoGeek (Post 123936)
or you can do something like...
:

  for(i=0;i<100;++i)
    a[i] = i+1;

  for(i=0;i<100;++i)
    swap(a[i], a[rand()%100]);


you should aslo give srand a call before calling rand or everytime you start the program you will get the same random numbers as you got last time you ran the program

jim mcnamara Feb 14th, 2007 1:17 PM

If you are dealing a deck of cards, infogeek's method is what you want. You can deal a card only once. If you are doing something with "random" selections, then repeats have to be allowed, because that is what random means.


All times are GMT -5. The time now is 1:56 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC