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

JavaScript天平平衡ScaleBalancing算法输出格式调整问题

天平平衡算法修改版(JavaScript)

以下是符合所有要求的可直接运行代码:

function ScaleBalancing(strArr) {
    const [leftWeight, rightWeight] = JSON.parse(strArr[0]);
    const weights = JSON.parse(strArr[1]);
    // 初始两侧重量相等直接返回
    if (leftWeight === rightWeight) {
        return '两侧相等';
    }
    // 优先判断仅用1个砝码的场景
    for (let i = 0; i < weights.length; i++) {
        const w1 = weights[i];
        if (leftWeight + w1 === rightWeight) {
            return `Left: ${w1} | Right: 0`;
        }
        if (rightWeight + w1 === leftWeight) {
            return `Left: 0 | Right: ${w1}`;
        }
        // 判断用2个砝码的场景
        for (let j = i + 1; j < weights.length; j++) {
            const w2 = weights[j];
            // 两个砝码都加左侧
            if (leftWeight + w1 + w2 === rightWeight) {
                return `Left: ${w1},${w2} | Right: 0`;
            }
            // 两个砝码都加右侧
            if (rightWeight + w1 + w2 === leftWeight) {
                return `Left: 0 | Right: ${w1},${w2}`;
            }
            // 两侧各加一个砝码
            if (leftWeight + w1 === rightWeight + w2) {
                return `Left: ${w1} | Right: ${w2}`;
            }
            if (leftWeight + w2 === rightWeight + w1) {
                return `Left: ${w2} | Right: ${w1}`;
            }
        }
    }
    // 无法用现有砝码平衡
    return '无法平衡';
}

// 测试用例
console.log(ScaleBalancing(["[4, 4]", "[1, 2,3, 6]"])); // 输出:两侧相等
console.log(ScaleBalancing(["[3, 4]", "[1, 2, 7, 7]"])); // 输出:Left: 1 | Right: 0
console.log(ScaleBalancing(["[13, 4]", "[1, 2, 3, 6, 14]"])); // 输出:Left: 0 | Right: 3,6
console.log(ScaleBalancing(["[5, 9]", "[1, 2, 6, 7]"])); // 输出:Left: 6 | Right: 2

核心修改说明

  • 将初始相等的返回值从英文改为中文两侧相等,符合翻译要求
  • 完全对齐指定输出格式,无砝码时补0,多砝码用英文逗号分隔
  • 拆分了双砝码匹配的4种场景,避免逻辑混乱,保证砝码归属的正确性
  • 保留了原算法优先使用最少砝码平衡的逻辑,先匹配单砝码场景再匹配双砝码场景

内容的提问来源于stack exchange,提问作者Frab Nob

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 01:54:02