let buffer = [0, 1, 2, 3, 4]; // 奖池
let buff_probability = [0.2, 0.2, 0.2, 0.2, 1]; // 概率
for (let i = 0; i < 10000; i++) {
const result = randomProbability(buffer, buff_probability);
console.log('result: ', result);
}
function randomProbability(elements, weightArr) {
var sum = 0;
var factor = 0;
var random = Math.random();
for (var i = weightArr.length - 1; i >= 0; i--) {
sum += weightArr[i]; // 统计概率总和
}
random *= sum; // 生成概率随机数
for (var i = weightArr.length - 1; i >= 0; i--) {
factor += weightArr[i];
if (random <= factor) return elements[i];
}
return null;
}