probability in javascript help?

后端 未结 6 1851
-上瘾入骨i
-上瘾入骨i 2020-12-28 10:06

Sorry, I\'m new to JS and can\'t seem to figure this out: how would I do probability?

I have absolutely no idea, but I\'d like to do something: out of 100% chance, m

6条回答
  •  [愿得一人]
    2020-12-28 10:33

    Something like this should help:

    var threshhold1 = 30.5;
    var threshhold2 = 70.5;
    var randomNumber = random() * 100;
    if (randomNumber < threshhold1) {
       func1()
    }
    else if (randomNumber < threshhold2) {
       func2()
    }
    else {
       func3()
    }
    

    This will execute func1() with 30.5% probability, func2() with 40%, and func3() with 29.5%.

    You could probably do it more elegantly using a dictionary of threshholds to function pointers, and a loop that finds the first dictionary entry with a threshhold greater than randomNumber.

提交回复
热议问题