侧边栏壁纸
  • 累计撰写 225 篇文章
  • 累计创建 275 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

概率计算

DGF
DGF
2017-05-15 / 0 评论 / 0 点赞 / 27 阅读 / 0 字

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

0

评论区