javascript - Selection of variant based on probabilities -
sorry not english. new theme me (i mean speak first time using english :) can make mistakes).
so problem.
i have, example 3 variants. probabilities : 0.5, 0.2, 0.3 example. how can choose variant choose right now? think can this way:
- create interval [0; 1].
- separate smaller intervals (3 in example). [0; 0.5), [0.5, 0.7), [0.7, 1].
- generate random number 0 1 (float, double)
- detect interval number belongs to
for example 0.3 generated, 1st interval, first variant.
- is right approach?
- how code using javascript or @ least show pseudo code.
p.s.: have dynamic amount of variants every time.
thank you.
it right approach , can working this:
var rand = math.random(); if (rand < 0.5) { // first variant } else if (rand < 0.7) { // second variant } else { // third variant }
you don't need completly specify intervals in conditions because math.random()
generates real numbers interval [0,1].
for dynamic amount of variants can create array of corresponding right ends of intervals , loop trough it:
var intervals = [0.1, 0.25, 0.28] // note array has sorted work var rand = math.random(); for(i in intervals) { if (rand < intervals[i]) { // i-th variant break; } }
Comments
Post a Comment