Loading...
Loading...
You are given a stream of pairs of doubles (x, v) that arrives one pair at a time. For the current n pairs, the weight of the value v[i] is exp(x[i]) / (exp(x[0]) + exp(x[1]) + ... + exp(x[n - 1])). The softmax-weighted average of the values is the sum of every value multiplied by its weight.
Implement the class SoftmaxAggregator:
SoftmaxAggregator() creates an empty aggregator.add(x, v) adds the pair (x, v) to the aggregator.value() returns the softmax-weighted average of the pairs added since the aggregator was created or last reset.size() returns the number of pairs added since the aggregator was created or last reset.reset() removes all pairs.You can assume value is only called while the aggregator holds at least one pair. Note that a key x may be large, but the softmax-weighted average is always a finite number between the smallest and the largest of the current values.
-10^9 <= x <= 10^9 for every key passed to add-10^6 <= v <= 10^6 for every value passed to add1 and 10^4 calls in total, including the constructorvalue is called only while the aggregator holds at least one pairBoth keys are 0, so the two values carry equal weight and the answer is (1 + 3) / 2 = 2. Two pairs are present, so size returns 2.
With a single pair the value has all the weight, so the answer is 5. The key 1000 outweighs the key 0 so heavily that the second pair takes essentially all the weight, so the second answer is 7.
The first two values weigh the same, so their average is 3. After reset the aggregator is empty and size returns 0, then the lone pair added afterwards gives 10.