You are given n numbers as well as n probabilities that sum up to 1. Write a function to generate one of the numbers with its corresponding probability.
Input: numbers =[1,2,3,4], probabilities =[0.1,0.5,0.2,0.2]Output: Returns 110% of the time,250% of the time, and 3 or 420% of the time.Explanation: The function should utilize the given probabilities to return the numbers based on their probabilities.
The task requires generating a number based on pre-defined probabilities. To achieve this, we can use the concept of cumulative probabilities. We transform the given probabilities into cumulative probabilities and use a uniformly generated random number to determine the output number according to these cumulative probabilities.
publicclassSolution {
privateint[] numbers;
privatedouble[] cumulativeProbabilities;
private Random random;
publicvoidinit(int[] numbers, double[] probabilities) {
this.numbers= numbers;
this.cumulativeProbabilities=newdouble[probabilities.length];
this.random=new Random();
cumulativeProbabilities[0]= probabilities[0];
for (int i = 1; i < probabilities.length; i++) {
cumulativeProbabilities[i]= cumulativeProbabilities[i - 1]+ probabilities[i];
}
}
publicintgenerate() {
double r = random.nextDouble();
for (int i = 0; i < cumulativeProbabilities.length; i++) {
if (r < cumulativeProbabilities[i]) {
return numbers[i];
}
}
return numbers[numbers.length- 1]; // In case of precision issues with double comparisons. }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution:
def __init__(self):
self.numbers = []
self.cumulative_probabilities = []
definit(self, numbers: List[int], probabilities: List[float]) ->None:
self.numbers = numbers
self.cumulative_probabilities = [0] * len(probabilities)
self.cumulative_probabilities[0] = probabilities[0]
for i in range(1, len(probabilities)):
self.cumulative_probabilities[i] = self.cumulative_probabilities[i -1] + probabilities[i]
defgenerate(self) -> int:
r = random.random()
for i, cp in enumerate(self.cumulative_probabilities):
if r < cp:
return self.numbers[i]
return self.numbers[-1] # In case of precision issues with float comparisons.