let buffer = [0,1,2,3,4]; // 奖池
let buff_probability = [0.2, 0.2, 0.2, 0.2, 0.2]; // 概率
randomProbability(buffer, buff_probability )
function randomProbability(arr1, arr2) {
var sum = 0,
factor = 0,
random = Math.random();
for(var i = arr2.length - 1; i >= 0; i--) {
sum += arr2[i]; // 统计概率总和
};
random *= sum; // 生成概率随机数
for(var i = arr2.length - 1; i >= 0; i--) {
factor += arr2[i];
if(random <= factor) return arr1[i];
};
return null;
}
网友评论