I'm searching for an algorithm (no matter what programming language, maybe Pseudo-code?) where you get a random number with different probability's.
For example:
A random Generator, which simulates a dice where the chance for a '6' is 50% and for the other 5 numbers it's 10%.
The algorithm should be scalable, because this is my exact problem:
I have a array (or database) of elements, from which i want to select 1 random element. But each element should have a different probability to be selected. So my idea is that every element get a number. And this number divided by the sum of all numbers results the chance for the number to be randomly selected.
Anybody know a good programming language (or library) for this problem? The best solution would be a good SQL Query which delivers 1 random entry. But i would also be happy with every hint or attempt in an other programming language.
A simple algorithm to achieve it is:
sum[i] = p1 + p2 + ... + pi
. This is done only once.r
with uniform distribution over[0,sum[n])
, and binary search for the first number higher than the uniformly distributed random number. It can be done using binary search efficiently.It is easy to see that indeed the probability for
r
to lay in a certain range[sum[i-1],sum[i])
, is indeedsum[i]-sum[i-1] = pi
(In the above, we regard
sum[-1]=0
, for completeness)For your cube example:
You have:
First, calculate
sum
array:Then, each time you need to draw a number: Draw a random number
r
in[0,1)
, and choose the number closest to it, for example: