您的位置:首页 > 其它

Write a function that generates one of 3 numbers according to given probabilities

2014-06-05 19:50 537 查看
You are given a function rand(a, b) which generates equiprobable random numbers between [a, b] inclusive. Generate 3 numbers x, y, z with probability P(x), P(y), P(z) such that P(x) + P(y) + P(z) = 1 using the given rand(a,b) function.

The idea is to utilize the equiprobable feature of the rand(a,b) provided. Let the given probabilities be in percentage form, for example P(x)=40%, P(y)=25%, P(z)=35%..

// This function generates 'x' with probability px/100, 'y' with
// probability py/100  and 'z' with probability pz/100:
// Assumption: px + py + pz = 100 where px, py and pz lie
// between 0 to 100
int random(int x, int y, int z, int px, int py, int pz) {
// Generate a number from 1 to 100
int r = rand(1, 100);

// r is smaller than px with probability px/100
if (r <= px)
return x;

// r is greater than px and smaller than or equal to px+py
// with probability py/100
if (r <= (px+py))
return y;

// r is greater than px+py and smaller than or equal to 100
// with probability pz/100
else
return z;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐