Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ algorithm to select two random numbers from a range, with minimal distance

Tags:

c++

I have an std::vector initialized with numbers from 1 to 100

std::vector<int> vec;
for(int i = 1; i < 101; i++)
  vec.push_back(i);

I want to select two random integers that have a minimal distance (for example minimal distance can be 10).

If num1, num2 are the numbers:

num2 - num1 > distance

I am using the following method to select a random integer between ranges:

int getRandomValue(int from, int to)
        {
                std::random_device seeder;
                std::mt19937 engine(seeder());
                std::uniform_int_distribution<int> dist(from, to);
                return dist(engine);
        }

How can I generate num2 and num1?

like image 383
cateof Avatar asked Jul 04 '26 15:07

cateof


1 Answers

You may use something like the following:

num1 = getRandomValue(minRange, maxRange - distance - 1);
num2 = getRandomValue(num1 + distance + 1, maxRange);

Note though that it would not be an uniform distribution for the pair result.

like image 71
Jarod42 Avatar answered Jul 07 '26 06:07

Jarod42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!