Reputation: 853
I'me making a Pacman game in opengl and I need to generate 2 diferent numbers 0 or 1, that are responsable for the direction of my pacman deppending on the direction he's taking.
How can I generate a number with rand() function that generates 75% of randomness for one number and 25% of randomness for the other?
If I make:
n = rand() % 3;
It will get 2 different numbers. The problem is the percent of randomness I don't know how to make. I can make it with a cicle and a counter. But I was told I could do It directly in the rand() function. I search but I couldnt find nothing concrete on google.
Upvotes: 0
Views: 3067
Reputation: 88155
Use the <random>
library. The bernoulli_distribution will generate true with a given probability p, and false with probability 1-p.
#include <random>
#include <iostream>
#include <algorithm>
#include <iterator>
int main() {
std::generate_n(std::ostream_iterator<bool>(std::cout," "), 10,
std::bind(std::bernoulli_distribution(0.25), std::mt19937()));
}
prints:
1 0 0 1 0 0 1 0 0 0
Upvotes: 3
Reputation: 3638
You can always go with a equally distributed random range from a
to b
and check your condition on the value like this:
if((rand() % 100)>=75)
// 25%
;
else
// 75 %
;
Upvotes: 2
Reputation: 96109
rand() gives you a random number between 0 and RAND_MAX (typical 32k)
So half the values will be between 0 and RAND_MAX/2, 1/3 will be between 0 and RAND_MAX/3 and 2/3 will be between RAND_MAX/3 and RAND_MAX.
Is that enough of a hint?
Upvotes: 2