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:

  1. create interval [0; 1].
  2. separate smaller intervals (3 in example). [0; 0.5), [0.5, 0.7), [0.7, 1].
  3. generate random number 0 1 (float, double)
  4. detect interval number belongs to

for example 0.3 generated, 1st interval, first variant.

  1. is right approach?
  2. 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

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -