带权重的随即函数 Weighted Random

带权重的随即函数 Weighted Random
 1  function  buildFunction(productList, productWeight){
 2                   var  totalweight  =  eval(productWeight.join( " + " ))
 3                   var  weighedProducts  =   new  Array()
 4                   var  currentProducts  =   0
 5                   while  (currentProducts  <  productList.length) {
 6                       for  (i  =   0 ; i  <  productWeight[currentProducts]; i ++ ) {
 7                          weighedProducts.push(productList[currentProducts]);
 8                      }
 9                      currentProducts ++
10                  }
11                   return   function (){
12                       var  randomnumber  =  Math.floor(Math.random()  *  totalweight)
13                       return  (weighedProducts[randomnumber]);
14                  };
15              };
16               var  productList  =  [ " AK-47 " " Blade " " Food " " ByondGod " ]
17               var  productWeight  =  [ 200 20 4 1 ];
18               var  myFun  =  buildFunction(productList, productWeight);
19               for  ( var  i  =   0 ; i  <   100 ; i ++
20                  document.writeln((i + 1 ) + " : " + myFun())

你可能感兴趣的:(带权重的随即函数 Weighted Random)