Finite Weighted Outcome Expectation
Problem statement
Compute the expected value of a finite random experiment, such as rolling a die or spinning a wheel.
For this exercise, assume the experiment is described by two equally sized arrays, values and weights. Entry i has integer outcome values[i] and positive integer weight weights[i]. The probability of selecting that entry is its weight divided by the sum of all weights. Exactly one entry is selected; there are no repeated trials or stopping rules.
Return the expected outcome as a string numerator/denominator in lowest terms. The denominator must be positive. A zero result is 0/1, and an integer result still has denominator 1. Do not round or return a decimal approximation.
Repeated values represent separate entries: retain every entry's weight. Array order has no effect on the result. All inputs satisfy the constraints.
Function
expectedValue(values: int[], weights: int[]) → StringExamples
Example 1
values = [1,2,3,4,5,6]weights = [1,1,1,1,1,1]return = "7/2"The six faces are equally likely. Their mean is21/6, which reduces to 7/2.
Example 2
values = [-2,4,10]weights = [1,2,1]return = "4/1"The sector probabilities are 1/4,2/4,1/4. The expected outcome is(-2+8+10)/4=4, returned as 4/1.
Example 3
values = [-3,2]weights = [2,3]return = "0/1"The weighted contributions are -6 and 6, so the expectation is 0 and its canonical fraction is 0/1.
Constraints
1 <= values.length = weights.length <= 256.-1000000 <= values[i] <= 1000000.1 <= weights[i] <= 1000000.- Use signed 64-bit arithmetic for weighted sums; the absolute numerator before reduction is at most
256 × 1012.