Select element from array with probability proportional to its value

拈花ヽ惹草 提交于 2019-12-03 02:55:30

The usual technique is to transform the array into an array of cumulative sums:

 [10 60 5 25]  --> [10 70 75 100]

Pick a random number in the range from zero up to the cumulative total (in the example: 0 <= x < 100). Then, use bisection on the cumulative array to locate the index into the original array:

Random variable x      Index in the Cumulative Array      Value in Original Array
-----------------      -----------------------------      ----------------------
 0 <= x < 10                      0                            10
10 <= x < 70                      1                            60
70 <= x < 75                      2                             5
75 <= x < 100                     3                            25 

For example, if the random variable x is 4, bisecting the cumulative array gives a position index of 0 which corresponds to 10 in the original array.

And, if the random variable x is 72, bisecting the cumulative array gives a position index of 2 which corresponds to 5 in the original array.

For an inverse proportion, the technique is exactly the same except you perform an initial transformation of the array into its reciprocals and then build the cumulative sum array:

[10 60 5 25]  -->  [1/10  1/60  1/5  1/25]  -->  [1/10  7/60  19/60  107/300]
user3107673

For Inverse proportionality:

  1. sum the array
  2. Pick a random number between 0 and (n-1)*sum -1
  3. Accumulate sum-value starting from the beginning until you are >= to the random value.

This is for proportional

Note: All values must be positive for this to work.

  1. sum the array
  2. Pick a random number between 0 and the sum-1
  3. Accumulate the values starting from the beginning of the array until you are >= to the random value.

I faced with the same problem and come up with some simple solution. Not the perfect, but suitable for some cases.

You have array with some numbers [1,2,3,...] and you need to select a value with some probability [10,5,20,...] just make new array and repeat each value as much times as much probability it has, eg

arr[] = [1,1,1,1,...(10 times),2,2,2,..(5 times),3,3,3,3,...(20 times)];

And them just get random number from 0 to new array length and get your value with number with desirable probability.

int r = Random(0,arr.count);
int value = arr[r];

As I mention it's not perfect and also it's not memory efficient algorithm, but it works.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!