How to get random number with each number has its own probability [duplicate]

最后都变了- 提交于 2019-12-23 00:25:17

问题


For example, I want to get random number from set S = {0, 1, 2, 3}. But instead of each number has same probability to shown (which is 25%), now I have different probability for each number, let say {50%, 30%, 20%, 10%}. How do I code this? In Java or C# (I prefer C#).


回答1:


The Alias Method is by far my favorite for doing this.

http://code.activestate.com/recipes/576564-walkers-alias-method-for-random-objects-with-diffe/

I haven't reviewed this code but it is a top google result.

Here is another much better explanation

http://pandasthumb.org/archives/2012/08/lab-notes-the-a.html

I actually use this question for interviews quite often since if you have never seen it before it can be pretty puzzling.

If the above is too much for you to implement there is a simpler one loop through the input solution.

Using PHP since it is easier to just show the code.

function getNumberFromDistribution($dist) {
    $totalProbability = 0;
    $randomNumber = mt_rand(0, mt_getrandmax()) / mt_getrandmax();  //uniform random number between 0-1
    foreach($dist as $number => $chance) {
        if (($totalProbability += $chance) <= $randomNumber) {
            return $number;
        }
    }

    return null; //only reachable on bad input
}



回答2:


If the set is small you can build an array that contains the right number of each value you need to get your distribution eg. 1 1 1 2 2 3 would provide 3 times the likelihood of getting a 1 as it does of getting a 3. You would then use the length of the array to determine the random number that you use as an index.



来源:https://stackoverflow.com/questions/15237781/how-to-get-random-number-with-each-number-has-its-own-probability

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