js 中奖几率计算!

		function getRand(obj){
			this.obj = obj;
			return this.init();
		}

		//获取几率总和
		getRand.prototype.sum = function(key){
			var self = this;
			var obj = this.obj;
			var sum=0;
			for(var i in obj){
				sum+=obj[i][key];
			}
			return sum;
		};

		//取得结果
		getRand.prototype.init = function(){
			var result = null;
			var self = this;
			var obj = this.obj;
			var sum = this.sum('prob');	//几率总和
			for(var i in obj){
				var rand = parseInt(Math.random()*sum);
				if(rand<=obj[i].prob){
					result = obj[i];
					break;
				}else{
					sum-=obj[i].prob;
				}
			}
			return result;
		};


		//几率数组
		var obj = [
			{name:'广告一',prob:30},
			{name:'广告二',prob:18},
			{name:'广告三',prob:39},
			{name:'广告四',prob:60},
			{name:'广告五',prob:73},
		];

		//使用方法
		// $result = new getRand(obj);

		//测试数据,循环1000次取得每个数据出现的次数
		var record = [];
		for(var i = 0;i<1000;i++){
			var result = new getRand(obj);
			var index=false;
			for(var j in record){
				if(record[j].name==result['name']){
					index = j;
					break;
				}
			}
			if(index!==false){
				record[index].num+=1;
			}else{
				record.push({name:result['name'],num:1});
			}
		}

		console.log(record);



执行结果
0:{name: "广告五", num: 331}
1:{name: "广告四", num: 262}
2:{name: "广告三", num: 194}
3:{name: "广告一", num: 132}
4:{name: "广告二", num: 81}

参照网络php几率计算函数:
function get_rand($proArr) { 
  $result = ''; 
  //概率数组的总概率精度 
  $proSum = array_sum($proArr); 
  //概率数组循环 
  foreach ($proArr as $key => $proCur) { 
    $randNum = mt_rand(1, $proSum);       //抽取随机数
    if ($randNum <= $proCur) { 
      $result = $key;             //得出结果
      break; 
    } else { 
      $proSum -= $proCur;           
    } 
  } 
  unset ($proArr); 
  return $result; 
}


你可能感兴趣的:(javascript)