Probability based event generation

I recently gave an interview in which I was asked about using a function that gives a random number between 0 and 1 to generate events according to a given probability distribution. Following is my solution to it.

Get the random number between 0 and 1.

Loop over the available events while adding their respective probabilities until the sum is equal to or greater than the random number generated and when the sum exceeds the generated random number return the respective event.

Code

Demo

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store