Get a random number focused on center

后端 未结 20 3041
离开以前
离开以前 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:39

    Here's a weighted solution at 3/4 40-60 and 1/4 outside that range.

    function weighted() {
    
      var w = 4;
    
      // number 1 to w
      var r = Math.floor(Math.random() * w) + 1;
    
      if (r === 1) { // 1/w goes to outside 40-60
        var n = Math.floor(Math.random() * 80) + 1;
        if (n >= 40 && n <= 60) n += 40;
        return n
      }
      // w-1/w goes to 40-60 range.
      return Math.floor(Math.random() * 21) + 40;
    }
    
    function test() {
      var counts = [];
    
      for (var i = 0; i < 2000; i++) {
        var n = weighted();
        if (!counts[n]) counts[n] = 0;
        counts[n] ++;
      }
      var output = document.getElementById('output');
      var o = "";
      for (var i = 1; i <= 100; i++) {
        o += i + " - " + (counts[i] | 0) + "\n";
      }
      output.innerHTML = o;
    }
    
    test();

提交回复
热议问题