Design a generic component that stores values with integer weights and can return a random value with probability proportional to its weight.
add(value: T, weight: Int)
pick(): T
(name can vary)
[(1,1), (2,1), (5,3)]
, then probabilities are:
1
: 20%,
2
: 20%,
5
: 60%
(3,5)
, probabilities become:
1
: 10%,
2
: 10%,
5
: 30%,
3
: 50%
Prioritize clarity, maintainability, and extensibility over micro-optimizing performance.
Add an API that supports expiration:
addWithExpiry(value: T, weight: Int, expireAfterMs: Int)
pick()
.
weight
is always positive.
value
merges weight or stores multiple entries.