有goldtree和greentree,获得它们的概率分别为5%和95%,实现代码如下:
class Percent {
constructor(oArr) {
this.oArr = oArr;
this.result = this.calculateResult();
}
calculateSum() {
return Object.values(this.oArr).reduce((sum, [weight]) => sum + weight, 0);
}
calculateResult() {
const sum = this.calculateSum();
const rand = Math.floor(Math.random() * sum) + 1; // 随机数从 1 到 sum
let cumulativeSum = 0;
for (const [_, [weight, value]] of Object.entries(this.oArr)) {
cumulativeSum += weight;
if (rand <= cumulativeSum) {
return value;
}
}
}
}
// 测试
const data = {
"1": [5, "goldTree"],
"2": [95, "greenTree"]
};
const percentInstance = new Percent(data);
console.log(percentInstance.result);
评论区