【问题标题】:All possible variations of terms to add up to sum in a given amount of piles?在给定数量的堆中加起来的所有可能的术语变化?
【发布时间】:2021-03-14 10:29:17
【问题描述】:

如何使用javascript在给定数量的堆中获取所有可能的术语变化以求和? 假设我的总和为 10,我想将其分成 4 堆,其中只有正项和零。

function getCombinations(sum, piles){
    ...
}
getCombinations(10,4);

在二维数组中返回类似的东西:

[
    [3,3,3,1],
    [3,3,1,3],
    [7,1,1,1],
    [10,0,0,0],
    ...
]

返回 [3,3,3,1] 和 [3,3,1,3] 作为不同的解决方案不是强制性的,最快的方法就可以了。我只会处理小数字,最大总和可能是 10。

这是计数硬币问题http://rosettacode.org/wiki/Count_the_coins 的变体,但我希望返回解决方案,我有一组给定的堆,我使用所有正项(和零),而不仅仅是特定的硬币值。

【问题讨论】:

    标签: javascript combinations


    【解决方案1】:

    这应该可以解决问题:

    const matrix = (num, cols) => {
      const matrix = [[num, ...[...Array(cols-1)].map(() => 0)]];
      const hashes = new Set;
      const coef = Math.pow(10, cols-1);
      let digits = 10 * coef - 1;
    
      while (digits-- >= coef) {
        const nums = ('' + digits).split('').map(d => +d);
        const hash = nums.sort((a, b) => b - a).join('');
        if (hashes.has(hash) || nums.reduce((a, b) => a + b, 0) !== num)
          continue;
        hashes.add(hash);
        matrix.push(nums);
      }
      return matrix;
    };
    
    console.log(matrix(10, 4));

    【讨论】:

      【解决方案2】:

      这是一种实用的方法:

      function getCombinations(sum, piles){
         var array =[];
            for(var i = 1; i <= piles; i ++) {
      
         var subArray = Array.apply(null, Array(4)).map(
              function () {  
                  return Math.floor(Math.random() * sum)});
       
         array.push(subArray);
       
      
        }
         return array;
      }
       var result = getCombinations(10,4);
      

      【讨论】:

      • 我得到一个未定义的数组。
      • 我已经编辑过了,你可以再试一次。 RETURN 关键字必须与返回的 ITEM 位于同一行。然后就可以工作了。
      • 这不符合我的预期。堆中的数字加起来应该是总和,就像在我的示例返回数组中一样。为此,我需要所有可能的组合。
      猜你喜欢
      • 1970-01-01
      • 2011-11-11
      • 1970-01-01
      • 1970-01-01
      • 2014-10-04
      • 1970-01-01
      • 2011-08-06
      • 2019-04-23
      相关资源
      最近更新 更多