TypeScript 实现加权随机选择

 首先,我们定义一个接口来表示项目,并创建一个包含权重的物品列表。

interface Item {
    name: string;
    weight: number;
}

const items: Item[] = [
    { name: "普通药水", weight: 70 },
    { name: "稀有药水", weight: 20 },
    { name: "传奇药水", weight: 10 }
];

接下来,我们实现一个函数来根据权重进行随机选择。

function weightedChoice(items: Item[]): string {
    // 计算总权重
    const totalWeight = items.reduce((sum, item) => sum + item.weight, 0);

    // 生成一个0到总权重之间的随机数
    const randomNum = Math.random() * totalWeight;

    // 根据随机数选择项目
    let cumulativeWeight = 0;
    for (const item of items) {
        cumulativeWeight += item.weight;
        if (randomNum < cumulativeWeight) {
            return item.name;
        }
    }

    // 保险措施:如果没有选中任何项目(理论上不应该发生),返回第一个项目
    return items[0].name;
}

// 示例调用
const results: { [key: string]: number } = {};
for (let i = 0; i < 100; i++) {
    const chosenItem = weightedChoice(items);
    if (results[chosenItem]) {
        results[chosenItem]++;
    } else {
        results[chosenItem] = 1;
    }
}

console.log(results);

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值