1. 程式人生 > >js 中獎機率計算!

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);