Simple
- Create an array of probabilities (sum to 1.0), in
O(n)
time - Generate a random number between 0.0 and 1.0
- Iterate through the array, in
O(n)
time:- if the random number < the probability of the element, stop
- otherwise decrement the random number by the probability and move to next element
- The answer is the number corresponding to the element you stopped at
Complex
- Create an array of cumulative probabilities and store them in an array, in
O(n)
time (this array should have increasing values) - Generate a random number between 0.0 and 1.0
- Do a binary search to find the smallest element that is
>=
the random number, inO(log(n))
time. - The answer is the number corresponding to the element you stopped at
I have not included the necessary corner cases to address. I am sure you can do it yourself.