请求将Python加权随机选择代码转换为JavaScript语法
权重随机选择的JavaScript实现
以下是对应你提供的Python代码的可用JavaScript实现:
// 定义选项和对应的权重 const options = [["1","1","1"],["39","39","39"],["10","10","10"],["19","19","19"],["1","1","1"], "2", "lose"]; const weights = [0.2, 0.8, 1, 1, 2, 75, 20]; // 实现权重随机选择函数 function weightedRandomChoice(options, weights) { // 计算累积权重数组 const cumulativeWeights = []; let totalWeight = 0; for (const weight of weights) { totalWeight += weight; cumulativeWeights.push(totalWeight); } // 生成0到总权重之间的随机数 const random = Math.random() * totalWeight; // 找到对应选项 for (let i = 0; i < cumulativeWeights.length; i++) { if (random <= cumulativeWeights[i]) { return options[i]; } } // 兜底返回最后一个选项(理论上不会走到这) return options[options.length - 1]; } // 调用函数获取结果 const result = weightedRandomChoice(options, weights); console.log(result);
说明
- 这个函数完全模拟Python
random.choices的权重选择逻辑:无需预先归一化权重,直接根据权重的相对比例完成随机选择 - 原Python代码中重复的
["1","1","1"]选项会保留各自的权重配置,和原逻辑完全一致
内容的提问来源于stack exchange,提问作者Shahar
相关产品推荐
相关产品推荐

