问题
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