Reputation: 233
I know I can use std::discrete_distribution
like this:
std::default_random_engine generator;
std::discrete_distribution<int> distribution {2,2,1,1,2,2,1,1,2,2};
int p[10]={};
for (int i=0; i<100; ++i) {
int number = distribution(generator);
++p[number];
}
However, this is going to generate the numbers in the range of 0-9 as per the weight specified.
What can I do to generate the numbers within a user specified range, say for example, 24-33 or 95-104 etc but still using the distribution specified in discrete_distribution ?
Upvotes: 0
Views: 345
Reputation: 2673
when you have a function that returns a random number in range [r1,r2)
, and you want [min,max)
mathematics to help.
First we calculate d=(max-min)/(r2-r1)
and then we multiply the range [r1,r2)
by d so we get [d*r1,d*r2)
which we'll make [r1',r2')
, now you calculate diff=abs(min-r1)'
and sum that to the range [r1',r2')
, we used abs
because we want the difference without sign, and that my friend will get you the range you want, let's assume the function that returns in range [r1,r2)
is somerand()
then :
const int r1=0,r2=9
int myrand(const int min,const int max){
const int d=(max-min)/(r2-r1);
const int localrand=d*somerand();
return localrand + abs(min - d*r1);
}
you can check that the function returns min
when somerand()
returns r1
and your function returns max
when somerand()
returns r2
.
The solution above won't work with e.g. : r1=0,r2=2,min=0,max=3, in short max-min
should be divisible by r2-r1
.
Upvotes: -3
Reputation: 409
You can just add 24 or 95 to the number that is generated. At the beginning you have numbers from 0 to 9, when you add 24 to them you have numbers from 24 to 33.
Upvotes: 5