简体   繁体   中英

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));

So if I understood correctly, your function can return two booleans 0 and 1 . So I don't see the reason why you need min and max as parameters. I would do it like that, tell me if I didn't understand your problem properly.

    int randProb (int chance) {
    int random = (rand()%100)+1;
    
    if (random<=chance) {
        return 1;
    }
    else {
        return 0;
    }
}

To generate the random values you can use the following expression:

(rand() % (max - min + 1)) + min

Because you want the chance it is better to generate a number between 0 and 100, simulating percentages, and then return result < chance , namely:

int randProb(int chance) 
{
    int result = (rand() % (100 - 0 + 1)) + 0;
    return result < chance;
}

For a change=0, all values generated by rand() % 101 will be higher than or equal to 0 therefore result < chance will be always false ( ie, zero).

For a change=100, all values generated by rand() % 101 will be lower than or equal to 100 therefore result < chance will be always true .

Finally, for example for change=70, 70 out of the 100 values generated by rand() % 101 will be lower than or equal to 70 therefore result < chance will return true 70% of the time. And so one and so forth.

I don't know C, but I can give you some pseudocode that might help

Generate a random number between 0 and 100 if it is 1, then yourBoolean=true (or false, whatever you want to be rare) if not, then yourBoolean = what you want to be the 99% chance

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM