Random Pick with Weight
Try to solve the Random Pick with Weight problem.
We'll cover the following
Statement
You’re given an array of positive integers, weights
, where weights[i]
is the weight of the index.
Write a function, Pick Index(), which performs weighted random selection to return an index from the weights
array. The larger the value of weights[i]
, the heavier the weight is, and the higher the chances of its index being picked.
Suppose that the array consists of the weights . In this case, the probabilities of picking the indexes will be as follows:
-
Index 0:
-
Index 1:
-
Index 2:
Constraints:
-
weights.length
-
weights[i]
-
Pick Index() will be called at most times.
Note: Since we’re randomly choosing from the options, there is no guarantee that in any specific run of the program, any of the elements will be selected with the exact expected frequency.
Examples
Create a free account to view this lesson.
Continue your learning journey with a 14-day free trial.
By signing up, you agree to Educative's Terms of Service and Privacy Policy