【发布时间】:2017-12-29 18:34:56
【问题描述】:
我正在尝试返回至少覆盖提供的英尺数量所需的所有可能的独特“管道”组合。
这个问题类似于常见的硬币找零算法。
管道以 10'、25' 和 50' 为增量。
我查看了来自 here 和 here 的示例,它们似乎很接近,但是,我想返回所有可能的组合,而不是简单地计算它们。
这是我当前的代码:
let allCombos = [];
let pipeAmounts = [50, 25, 10];
function findPiping (feet, index, combo) {
if (index > pipeAmounts-1) {
return;
}
let makeCombos = (amountOfFeet, index, combo) => {
let currentPipe = pipeAmounts[index];
let newFeet = amountOfFeet - currentPipe;
combo.push(currentPipe);
if (newFeet >= currentPipe) {
makeCombos(newFeet, index, combo);
}
if (newFeet < currentPipe && newFeet > 0) {
makeCombos(newFeet, index, combo);
}
if (newFeet < 0) {
allCombos.push(combo);
combo = [];
makeCombos(feet, index+1, combo);
}
};
makeCombos(feet, index, combo);
}
findPiping(60, 0, []);
console.log('allCombos', allCombos)
目前我的代码只产生 2 种组合。
我怎样才能找到涵盖所需英尺数的所有可能组合?
【问题讨论】:
-
请阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您描述的问题。您没有显示此代码的任何输出,也没有指定您的问题:“我在思考它时遇到了麻烦”不是问题规范。这表明当地的导师,而不是 SO。
-
我已经修改了显示输出的帖子。问题“我怎样才能找到涵盖所需脚量的所有可能组合?”很清楚。
-
我刚刚安装了 Node v0.12.0 来解决这个问题。它声称有语法错误:
(function (exports, require, module, __filename, __dirname) { let allCombos = ^^^^^^^^^ SyntaxError: Unexpected identifier。你用的是什么版本? -
我只是在 chrome 中将它作为网页的一部分运行。虽然我验证了节点 v6.11.1 没有问题
标签: javascript algorithm permutation