I want to select a random number from 0,1,2,3...n
, however I want to make it that the chance of selecting k|0<k<n
will be lower by multiplication of x
from selecting k - 1
so x = (k - 1) / k
. As bigger the number as smaller the chances to pick it up.
As an answer I want to see the implementation of the next method:
int pickANumber(n,x)
This is for a game that I am developing, I saw those questions as related but not exactly that same:
Solving this gives you:
This gives you the probability you need to set to
pn
, and from it you can calculate the probabilities for all other p1,p2,...p_n-1Now, you can use a "black box" RNG that chooses a number with a distribution, like those in the threads you mentioned.
A simple approach to do it is to set an auxillary array:
Now, draw a random number with uniform distribution between
0
toaux[n]
, and using binary search (aux array is sorted), get the first value, which matching value inaux
is greater than the random uniform number you gotOriginal answer, for substraction (before question was editted):
For
n
items, you need to solve the equation:Solving this gives you:
This gives you the probability you need to set to
pn
, and from it you can calculate the probabilities for all other p1,p2,...p_n-1Now, you can use a "black box" RNG that chooses a number with a distribution, like those in the threads you mentioned.
Be advised, this is not guaranteed you will have a solution such that
0<p_i<1
for alli
, but you cannot guarantee one given from your requirements, and it is going to depend on values ofn
andx
to fit.