I have N values (integer). I'd like to know what is the most elegant way to randomly pick one of those values regarding a percentage. For example, for a 3 values example:
- Value 1 has 30% chance to get picked
- Value 2 has 12% chance to get picked
- Value 3 has 45% chance to get picked
I need this for a program i'm developing with Java but a pseudo code algorithm or a code in any other language would be ok.
Proposed algorithm:
n
) between0
and1
(assuming your random generator is well distributed)n < 0.30
return value1
n < 0.42
return value2
n < 0.87
return value3
One way of doing this without calculating values to use is