mercredi 23 décembre 2020

How can i generate a random boolean with probability (1 to 100) in C?

I need a function that generates a random boolean with a given probability from 1 to 100.

I've tried with this:

int randProb(int chance, int min, int max) { 
  int random = rand();
  if (random < (RAND_MAX) / chance / 10) 
    return -(random % (max - min + 1) + min);
  else
    return (random % (max - min + 1) + min);
}

but when I call it, passing 1 as a probability

randProb(1, 0, 1)

sometimes it returns 1, sometimes -1, and sometimes 0.

and when I call it, passing 100 as a probability

randProb(100, 0, 1)

sometimes returns 0 and sometimes 1, as it should work, with a probability of 100 it should always return 1.

Note time is initialized with this:

time_t t;
srand((unsigned) time(&t));



Aucun commentaire:

Enregistrer un commentaire