【问题标题】:How to calculate all possible combinations of values to cover dynamic amount?如何计算所有可能的值组合以涵盖动态金额?
【发布时间】:2017-12-29 18:34:56
【问题描述】:

我正在尝试返回至少覆盖提供的英尺数量所需的所有可能的独特“管道”组合。

这个问题类似于常见的硬币找零算法。

管道以 10'、25' 和 50' 为增量。

我查看了来自 herehere 的示例,它们似乎很接近,但是,我想返回所有可能的组合,而不是简单地计算它们。

这是我当前的代码:

 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


【解决方案1】:

这是一个递归,它返回至少涵盖所需 feet 的所有有效组合,给定 amounts 中提供的无限选择增量。

function f(feet, amounts, i, combo){
  if (feet <= 0 || i == amounts.length)
    return [combo];
  
  if (i == amounts.length - 1){
    while (feet > 0){
      combo.push(amounts[i]);
      feet -= amounts[i];
    }
    return [combo];
  }

  let combos = f(feet, amounts, i+1, combo.slice());

  while (feet > 0){
    combo.push(amounts[i]);

    feet -= amounts[i];

    combos = combos.concat(
      f(feet, amounts, i+1, combo.slice())
    );
  }
  
  return combos;
}

let pipes = [50, 25, 10];

console.log(JSON.stringify(f(60, pipes, 0, [])));

【讨论】:

  • 完美。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-10
  • 2014-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-23
相关资源
最近更新 更多