Generate A Weighted Random Number

前端 未结 11 2306
予麋鹿
予麋鹿 2020-11-22 12:40

I\'m trying to devise a (good) way to choose a random number from a range of possible numbers where each number in the range is given a weight. To put it simply: given the

11条回答
  •  长情又很酷
    2020-11-22 13:03

    Here are 3 solutions in javascript since I'm not sure which language you want it in. Depending on your needs one of the first two might work, but the the third one is probably the easiest to implement with large sets of numbers.

    function randomSimple(){
      return [0,0,0,0,0,0,0,0,1,2][Math.floor(Math.random()*10)];
    }
    
    function randomCase(){
      var n=Math.floor(Math.random()*100)
      switch(n){
        case n<80:
          return 0;
        case n<90:
          return 1;
        case n<100:
          return 2;
      }
    }
    
    function randomLoop(weight,num){
      var n=Math.floor(Math.random()*100),amt=0;
      for(var i=0;i

提交回复
热议问题