Question

Sorry for my not very good english. This is new theme for me (I mean I speak about it first time using english :) so I can make some mistakes).

So the problem.

I have, for example 3 variants. Probabilities are : 0.5, 0.2, 0.3 for example. How I can choose what variant to choose right now? I think I can do this this way:

  1. Create interval [0; 1].
  2. Separate it with smaller intervals (3 in my example). [0; 0.5), [0.5, 0.7), [0.7, 1].
  3. Generate a random number from 0 to 1 (float, double)
  4. Detect interval which number belongs to

For example 0.3 was generated, so 1st interval, so first variant.

  1. Is this right approach?
  2. How to code this using JavaScript or at least show it with pseudo code.

P.S.: I have dynamic amount of variants every time.

Thank you.

Was it helpful?

Solution

It is the right approach and you can get it working like 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 to completly specify the intervals in conditions because Math.random() generates real numbers from interval [0,1].

For dynamic amount of variants you can create array of corresponding right ends of intervals and loop trough it:

var intervals = [0.1, 0.25, 0.28] // note that the array has to be sorted for this to work

var rand = Math.random();

for(i in intervals) {
    if (rand < intervals[i]) {
        // i-th variant
        break;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top