Question:

How to make numbers from rand() func. not repeat? C

by  |  earlier

0 LIKES UnLike

cout<<"wining number is : ";

srand(time(0));

for(i=0;i<=size-1; i )

{

w[i] = 1 rand()B;

cout<<"["<<w[i]<<"] ";

}

cout<<endl;

this code stores a random number into an array then prints it out. but sometimes the number in the array repeats. i want to know how can i make the numbers not repeat itself or how to trap it...

 Tags:

   Report

4 ANSWERS


  1. You should use a seed value. You can use the system clock in ticks as the seed. Especially seconds/milliseconds give a good seed.

    The C runtime library gives good examples on how to use the seed value. THings are very unlikely to repeat for the first few trillion draws.


  2. First of all you are using C++, not C. If you are using C++ then you should specify this because certain things are done differently in C++ versus C.

    What you want is to generate all the numbers from 0 to size-1 once, in a random order. The easiest way to do this is by using the random_shuffle function provided in the algorithm header.

    And here is some code:

    #include &lt;iostream&gt;

    #include &lt;algorithm&gt;

    #include &lt;functional&gt;

    #include &lt;ctime&gt;

    #include &lt;cstdlib&gt;

    #define SIZE 100

    //Numbers generated will be in the range 0..SIZE-1

    #define NUM_PRINT 6

    //A total of NUM_PRINT numbers will be printed by the program

    using namespace std;

    int main()

    {

         int a[SIZE],i;

         for (i=0; i&lt;SIZE; i++)

              a[i]=i;

         srand(time(0));

         random_shuffle(a,a+SIZE);

         for (i=0; i&lt;NUM_PRINT; i++)

              cout &lt;&lt; a[i] &lt;&lt; endl;

         return 0;

    }

    Output:

    38

    13

    2

    48

    19

    27

  3. make another loop that goes through the numbers in the array already, and use another loop to say while the value is the same as the one in the array already, regenerate it.

    for (c=0;c&lt;i;c++){

    while(w[i]==w[c])

    w[i]=1 rand()B;

    }

    Something like that

  4. Since rand is (pseudo) random you can&#039;t stop it. If you want to catch it then keep a list of values already seen and use a continue if it happens.

Question Stats

Latest activity: earlier.
This question has 4 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.