You are given a function rand(a, b) which generates equiprobable random numbers between [a, b] inclusive. Generate one of three numbers x, y, or z with probabilities P(x), P(y), and P(z) such that P(x) + P(y) + P(z) = 1 using the given rand(a, b) function.
Input: x =1, y =2, z =3, P(x)=0.2, P(y)=0.5, P(z)=0.3Output: 2(or 1 or 3, according to the given probabilities)Explanation: Each number is returned with its specified probability.
Input: x =10, y =20, z =30, P(x)=0.1, P(y)=0.7, P(z)=0.2Output: 20(or 10 or 30, according to the given probabilities)Explanation: Each number is returned with its specified probability.
To generate one of three numbers with specified probabilities, we can use a uniform random number and map intervals of the range [0, 1) to each number according to its probability. This ensures each number is selected with the correct probability.
classSolution {
publicintgenerate(int x, int y, int z, double px, double py, double pz) {
double r = Math.random();
if (r < px) return x;
elseif (r < px + py) return y;
elsereturn z;
}
}
1
2
3
4
5
6
7
8
9
10
classSolution {
fungenerate(x: Int, y: Int, z: Int, px: Double, py: Double, pz: Double): Int {
val r = Math.random()
returnwhen {
r < px -> x
r < px + py -> y
else-> z
}
}
}
1
2
3
4
5
6
7
8
9
classSolution:
defgenerate(self, x: int, y: int, z: int, px: float, py: float, pz: float) -> int:
r = random.random()
if r < px:
return x
elif r < px + py:
return y
else:
return z
1
2
3
4
5
6
7
8
9
10
11
12
13
use rand::Rng;
impl Solution {
pubfngenerate(x: i32, y: i32, z: i32, px: f64, py: f64, pz: f64) -> i32 {
let r = rand::thread_rng().gen::<f64>();
if r < px {
x
} elseif r < px + py {
y
} else {
z
}
}
}