Probability based event generation

An Interview question I got

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