# Write a function that generates one of 3 numbers according to given probabilities in C++

C++Server Side ProgrammingProgramming

In this problem, we have to create a function that will generate three numbers based on the given probability.

For this, we will use the built-in random number generator function which is rand(a, b) which generates random numbers within the range [a, b] with equal probability.

Our task is to return only three numbers A, B, C which have the probability of occurrence as P(A), P(B), P(C) respectively and according to definition of probability P(A) + P(B) + P(C) = 1.

To create our function using rand(a,b). we will use its feature that the probability of occurrence of any number from a to b is the same. But we have to get A with probability P(A) and so on. So, for this, we will use percentage probabilities of the numbers i.e. if P(A) = 1/5, we will treat it as 20%.

So, the maximum probability percentage will be 100%, so we will generate a random number from 0 to 100 and based on the number generated we will return numbers between A, B, C based on the following conditions.

Case 1 − If the number generated is between 0 and P(A), return A.

Case 2 − If the number generated is between P(A) and P(A)+P(B), return B.

Case 3 − If the number generated is between P(A)+P(B) and 1{P(A)+P(B)+P(C)}, return C.

Let’s see an example that will make the concept clear,

## Input

A = 3 , P(A) = 35%
B = 43, P(B) = 50%
C = 90, P(C) = 15%

The program will return,

3 if the rand function generates number between 0 and 35.

43 if the rand function generates number between 35 and 85.

90 if the rand function generates number between 85 and 100.

Program to show the implementation of our logic,

## Example

Live Demo

#include<iostream>
using namespace std;
int randomABC(int A, int B, int C, int PA, int PB, int PC){
int randNumber = rand()%100+1;
if (randNumber <= PA)
return A;
if (randNumber <= (PA+PB))
return B;
else
return C;
}
int main(){
cout<<"Random number between 3, 45, 90 with given probabilities is : "<<randomABC(3, 43, 90, 35, 40, 25);
return 0;
}

## Output

Random number between 3, 45, 90 with given probabilities is : 3
Published on 15-Jul-2020 06:22:59