probability in javascript help?

后端 未结 6 1881
-上瘾入骨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:44

    // generate cumulative distribution function from weights
    function cdf(weights) {
        // calculate total
        var total = 0;
        for(var i=0; i cumul[i]); ++i) {};
        return i;
    }
    

    Code block to use the above

    // setup (do this once)
    var weights = [70,20,10];
    var cumul = cdf(weights)
    
    // get the index and pick the function
    var ran = Math.random(); // 0 : 1
    var func = funcs[selectInd(cumul,ran)]; 
    
    // call the function
    var someArgVal = 5;
    var myResult = func(someArgVal);
    
    // do it in one line
    var myResult = (funcs[selectInd(cumul,Math.random())])(someArgVal);
    

    Simplify calling code with a reusable object

    function CumulDistributor(cumul,funcs) {
        var funcArr = funcs;
        var cumulArr = cumul;
        function execRandomFunc(someArg) {
            var func = funcArr[selectInd(cumulArr,Math.random())];
            return func(someArg);
        }
    }
    
    // example usage
    var cdistor = new CumulDistributor(cumul,funcs);
    var myResult = cdistor.execRandomFunc(someArgValue);
    

提交回复
热议问题