mercredi 2 juin 2021

How rand() works in C?

I was reading the following question: Unique random number generation in an integer array

and want to improve the accepted answer.

First I want the field [0,N] not (0,n) so I removed the +1 like this:

int im = 0;
int vektor[10];
for (int in = 0; in < N && im < M; ++in)
{
    int rn = N - in;
    int rm = M - im;
    // Added this according to suggestions: srand(time(NULL));
    if (rand() % rn < rm)
    {
        vektor[im++] = in; // was vektor[im++] = in + 1;
    } /* +1 since your range begins from 1 */
}

assert(im == M);
  1. still I never saw N being chosen, why is that?

  2. why I need to add srand(time(NULL)); none explained it except that running the code without it will result in the same output.

  3. Don't we need to set the values of the vector to 0 at first?


regarding my note under the question the output was:

0 3 4 8 13 18 20 24 29 30


0 3 4 8 13 18 20 24 29 30




Aucun commentaire:

Enregistrer un commentaire