Get a random number focused on center

后端 未结 20 3054
离开以前
离开以前 2020-12-12 09:28

Is it possible to get a random number between 1-100 and keep the results mainly within the 40-60 range? I mean, it will go out of that range rarely, but I want it to be main

20条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-12 09:40

    Distribution

     5% for [ 0,39]
    90% for [40,59]
     5% for [60,99]
    

    Solution

    var f = Math.random();
    if (f < 0.05) return random(0,39);
    else if (f < 0.95) return random(40,59);
    else return random(60,99);
    

    Generic Solution

    random_choose([series(0,39),series(40,59),series(60,99)],[0.05,0.90,0.05]);
    
    function random_choose (collections,probabilities)
    {
        var acc = 0.00;
        var r1 = Math.random();
        var r2 = Math.random();
    
        for (var i = 0; i < probabilities.length; i++)
        {
          acc += probabilities[i];
          if (r1 < acc)
            return collections[i][Math.floor(r2*collections[i].length)];
        }
    
        return (-1);
    }
    
    function series(min,max)
    {
        var i = min; var s = [];
        while (s[s.length-1] < max) s[s.length]=i++;
        return s;
    }
    

提交回复
热议问题