【问题标题】:add counter to the n combinations of javascript array将计数器添加到 javascript 数组的 n 个组合中
【发布时间】:2020-01-25 20:59:31
【问题描述】:

这个程序应该从数组中输出许多可能的元素组合。我没有做的是在左侧为每个可能的组合添加一个计数器。第一个组合为“001”,第二个组合为“002”,依此类推,直到最后一个。我尝试使用 for 循环和 while-do 以多种方式做到这一点,但任何尝试都是失败的。

function combine(a, b, c) {

  if (b === 0) {
    console.log(three.join(" "));
    return;
  }

  for (var i = c; i <= a.length - b; i++) {
    three[three.length - b] = a[i];
    combine(a, b - 1, i + 1);
  }

}
const vegetables = ["carrot", "tomatoes", "potatoes", "celery", "pepper"];
const three = [];
three.length = 4;

combine(vegetables, three.length, 0);

【问题讨论】:

    标签: javascript arrays combinations counter


    【解决方案1】:

    您可以使用padStart 来生成您要查找的内容。像这样的

    const vegetables = ["carrot", "tomatoes", "potatoes", "celery", "pepper"];
    const three = [];
    three.length = 4;
    let counter = 1;
    function combine(a, b, c) {
      if (b === 0) {
        const counterForPrint = (counter++).toString().padStart(3, "0");
        console.log(`${counterForPrint} ${three.join(" ")}`);
        return;
      }
      for (let i = c; i <= a.length - b; i++) {
        three[three.length - b] = a[i]; combine(a, b - 1, i + 1);
      }
    }
    
    combine(vegetables, three.length, 0);

    顺便说一句,您可以使用一些库来生成组合。它使事情变得非常清晰,让您专注于实际逻辑。像这样的

    const Combinatorics = require("js-combinatorics");
    const vegetables = ["carrot", "tomatoes", "potatoes", "celery", "pepper"];
    
    const possibleCombinations = Combinatorics.permutation(vegetables);
    let counter = 1;
    possibleCombinations.forEach(element => {
      const counterForPrint = (counter++).toString().padStart(3, "0");
      console.log(`${counterForPrint} ${element}`);
    });
    

    【讨论】:

      猜你喜欢
      • 2014-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多