You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 10:21:58