mercredi 2 juin 2021

C, rand() gives same result?

Reading the accepted answer here: Unique random number generation in an integer array

I want to edit the code so it start from 0 and ends with M (including both)

for 0 as the answerer wrote I need to remove +1 from the code:

#define M 10
#define N 100

int in, im;

im = 0;

for (in = 0; in < N && im < M; ++in) {
  int rn = N - in;
  int rm = M - im;
  if (rand() % rn < rm)    
    /* Take it */
    vektor[im++] = in + 1; /* +1 since your range begins from 1 */
}

assert(im == M);

But still this code doesn't include M.

  1. How to fix this?

  2. If I run this code twice (copy and paste) I get exactly same results, how to save this too?




Aucun commentaire:

Enregistrer un commentaire