Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I exclude a number or subrange of numbers inside a range of random numbers in modern C++?

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.
Example 1: Let's say, I want to generate a random number between 0 and 100, but this number can never be 4.
Example 2: Let's say, I want to generate a random number 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?

like image 947
AxoyTO Avatar asked Dec 01 '22 13:12

AxoyTO


1 Answers

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.

like image 125
463035818_is_not_a_number Avatar answered Dec 05 '22 07:12

463035818_is_not_a_number