Write an algorithm to generate any one of the given n numbers according to given probabilities.

For example, consider the following integer array and their probabilities. The solution should return 1 with 30% probability, 2 with 10% probability, 3 with 20% probability, and so on for every array element.

nums[] = { 1, 2, 3, 4, 5 };
probability[] = { 30, 10, 20, 15, 25 };    // total probability should sum to 100%

Practice this problem

Algorithm:

  1. Construct a sum array S[] from the given probability array P[], where S[i] holds the sum of all P[j] for 0 <= j <= i.
  2. Generate a random integer from 1 to 100 and check where it lies in S[].
  3. Based on the comparison result, return the corresponding element from the input array.

 
The implementation can be seen below in C, C++, Java, and Python:

C


Download  Run Code

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output (will vary):
 
1 ~ 30.3368%
2 ~ 10.063%
3 ~ 20.1714%
4 ~ 15.1579%
5 ~ 24.2709%