求总爪数为K时金丝雀、鹦鹉、猫的数量组合及代码修正
问题分析与代码修改
原代码存在的核心问题:
- 仅硬编码处理了总爪数为8的特殊情况,其他数值完全未正确处理
- while循环内直接break,仅输出一组“全最大值”的组合,完全未遍历所有合法组合
正确推导思路
金丝雀、鹦鹉各有2爪,猫有4爪,总爪数公式可简化为:金丝雀数量 + 鹦鹉数量 + 2×猫数量 = K/2
其中三个动物的数量均为非负整数。基于此公式,我们可以通过嵌套遍历枚举所有合法组合:
- 先验证K是否为正偶数,否则直接提示非法输入
- 计算简化后的总数值
total = K / 2 - 遍历猫的所有可能数量(范围是0到
Math.floor(total / 2),因为2×猫数量不能超过total) - 对每个猫的数量,计算剩余可分配给金丝雀和鹦鹉的数值
remaining = total - 2×猫数量 - 遍历金丝雀的所有可能数量(范围是0到remaining),鹦鹉数量自动为
remaining - 金丝雀数量,每一组都输出
修改后的代码
function calculateAnimals(maxPaws) { // 合法性判断:总爪数必须是正偶数 if (maxPaws <= 0 || maxPaws % 2 !== 0) { console.log("Sorry, not equal amount of paws"); return; } const total = maxPaws / 2; const maxCat = Math.floor(total / 2); // 遍历所有可能的猫数量 for (let cat = 0; cat <= maxCat; cat++) { const remaining = total - 2 * cat; // 遍历所有可能的金丝雀数量,鹦鹉数量自动得出 for (let canary = 0; canary <= remaining; canary++) { const parrot = remaining - canary; console.log(`Total: ${canary} canary, ${parrot} parrot, ${cat} cat`); } } } // 测试示例 calculateAnimals(20);
运行后会输出总爪数为20时的所有合法组合,比如:
- Total: 0 canary, 10 parrot, 0 cat
- Total: 1 canary, 9 parrot, 0 cat
- ...
- Total: 0 canary, 0 parrot, 5 cat
内容的提问来源于stack exchange,提问作者Ivan
相关产品推荐
相关产品推荐

