说我有一张地图:
现在,我需要使用weighted random selection随机选择资源。但是,负载最高的资源应该具有最低的选择概率[例如,R2应该具有最低的概率]。那么,我现在正在做的计算概率是:
At first taking sum of values of the map say, totalWeight:
totalWeight = 1+3+1+1 = 6 (for above example)
newTotalWeight = (totalWeight - load of R1) + .... + (totalWeight - load of R4)
= totalWeight * (noOfElements-1)
= 6 * (4-1) = 18
Finally,
p(selecting a resource R) = (totalWeight - current load of R) / newTotalWeight
So, for above example:
p(selecting R1) = (6 - 1) / 18 = 5/18
p(selecting R2) = (6 - 3) / 18 = 3/18
p(selecting R3) = (6 - 1) / 18 = 5/18
p(selecting R4) = (6 - 1) / 18 = 5/18
p(R1, R2, R3, R4) = (5/18, 3/18, 5/18, 5/18)
这正是我想要的。现在,离散逆变换方法:
Generate U~U(0,1)
if U <= p(R1) selectedResource = R1;
if p(R1) < U <= (p(R1) + p(R2)) selectedResource = R2;
.......
可用于选择资源。
但我正在使用BOOST的{_ 3}}的discrete_distribution。
现在,每当资源负载发生变化时,我会使用上面的等式重新计算每个资源的概率,并重复整个过程。
我做得对吗还是有其他有效的方法吗?
答案 0 :(得分:0)
你在找这个:
boost::mt19937 mt(42);
boost::random::discrete_distribution<int, Weight> dist({1,3,1,1});
auto genR = [&] { return static_cast<Resource>(dist(mt)); };
for (int i = 0; i<10; ++i)
std::cout << genR() << "\n";
#include <boost/random.hpp>
#include <boost/random/discrete_distribution.hpp>
#include <boost/random/piecewise_linear_distribution.hpp>
enum Resource { R1, R2, R3, R4, R5 };
using Weight = int;
std::ostream& operator<<(std::ostream& os, Resource r) {
return os << "R" << std::to_string(1+r);
}
int main()
{
using namespace std;
boost::mt19937 mt(42);
boost::random::discrete_distribution<int, Weight> dist({1,3,1,1});
auto genR = [&] { return static_cast<Resource>(dist(mt)); };
for (int i = 0; i<10; ++i)
std::cout << genR() << "\n";
}
打印例如
R2
R4
R1
R1
R1
R4
R3
R1
R1
R2