I have:
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<int> probability(0, 100);
I want to exclude some numbers in this range of probabilities.
Example1: Let's say, I want to generate a random number in between 0 and 100, but this number can never be 4.
Example2: Let's say, I want to generate a random number in between 0 and 100, but this number can never be any number between 4 and 7.
I wonder if it is possible to achieve in modern C without using std::rand?
Thanks in advance!
CodePudding user response:
If you want to stay with a uniform_int_distribution
you can do it manually like this:
Example1: Let's say, I want to generate a random number in between 0 and 100, but this number can never be 4.
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<int> distribution(0,99);
auto temp = distribution(mt);
auto random_number = (temp < 4) ? temp : temp 1;
Example2: Let's say, I want to generate a random number in between 0 and 100, but this number can never be any number between 4 and 7.
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<int> distribution(0,96);
auto temp = distribution(mt);
auto random_number = (temp < 4) ? temp : temp 4;
This could be generalize to write a function random_int_between_excluding(int first, int last, std::vector<int> exclude)
, though at some point it will be simpler to follow NathanOlivers suggestion and use a std::discrete_distribution
instead.
CodePudding user response:
If you want to miss out 4 say, then a very good way (which doesn't compromise any statistical properties of the generator), is to draw in the half-open interval [0, 99) then add 1 if the number is 4 or greater.
You do something similar to omit numbers in a range.
This method is a surprisingly good way of modelling the quantile function associated with the desired probability distribution.
CodePudding user response:
There is an option to do it manually within a reasonable range of numbers..., create a look up table and exclude the numbers that are invalid:
static int rand_pool[]{1,2,3,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23}; //no number 4
srand((int)time(0));
int random_number = rand_pool[rand() % 22];