js抽奖概率算法
直接通过数组中prob值来控制概率,值越大概率越高,值越小,概率越低
<script>
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: 1
},
{
name: '结果二',
prob: 5
},
{
name: '结果三',
prob: 39
},
{
name: '结果四',
prob: 60
},
{
name: '结果五',
prob: 703
},
];
//使用方法
// $result = new getRand(obj);
//测试数据,循环1000次取得每个数据出现的次数
var record = [];
for (var i = 0; i <= 100; i++) {
var result = new getRand(obj);
var index = false;
for (var j in record) {
if (record[j].name == result['name']) {
index = j;
document.write("第"+i+"次,"+record[j].name+"<br>");
break;
}
}
if (index !== false) {
record[index].num += 1;
} else {
record.push({
name: result['name'],
num: 1
});
}
}
</script>
关注公众号:拾黑(shiheibook)了解更多
友情链接:
下软件就上简单下载站:https://www.jdsec.com/
四季很好,只要有你,文娱排行榜:https://www.yaopaiming.com/
让资讯触达的更精准有趣:https://www.0xu.cn/