I have a simple array (or set if you prefer) of integers, let’s call it X. I also have another array W that stores the “weight” of elements in array X. The “weight” indicates how likely n-th element should be selected. Now I need a method (algorithm) to (pseudo) randomly select one element from array/set X according to its “weight” defined in array W.
For example, if my W looks like this:
W[0] = 2;
W[1] = 4;
W[2] = 6;
that means probability of selecting N-th item from array X is:
X[0] = 16.6%
X[1] = 33.3%
X[2] = 50%
so method get_pseudorandom_item(X) should return 2-nd item around half of all times.
Any ideas or suggestions how to implement this (in any programming language) are much appreciated.
Thanks.
Generate an array P with the partial sums of the weights, i.e.
(P0 = W0), (P1 = W0 + W1), …, (Pn = W0 + W1 + … + Wn)
(you can do that within W, actually, if you don’t need the weights afterwards).
Generate a random number r in [0, Pn) where Pn denotes the last such sum (i.e. the sum of all weights).
Find the index k of the smallest (first) partial sum larger than the number you generated:
Pk > r ∧ ∀ a < k: Pa < r
Use that index to select your actual element: Xk