C ++ for selecting two random numbers from a range with minimum distance
I have a 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 numbers that have a minimum distance (for example, the minimum distance might be 10).
If num1, num2 are 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?
+3
cateof
source
to share
3 answers
You can use something like the following:
num1 = getRandomValue(minRange, maxRange - distance - 1);
num2 = getRandomValue(num1 + distance + 1, maxRange);
Note that this would not be an even distribution for the pair result.
+4
Jarod42
source
to share
you can randomize num1 for example and sum the distance, then you have num2.
But you have to be careful, the reason num1 must be below or equal to 100-distance
or oposite randomize num2 from 10 to 100 and num1 = num2-distance
0
Gabri T
source
to share
#include <cstdlib>
a = rand() % 90;
b = a + 10;
a less, b more [/ p>
0
MonSh1rE
source
to share