【问题标题】:Group array base on maximum and length根据最大值和长度分组数组
【发布时间】:2020-02-14 02:27:08
【问题描述】:

很难对这个数组进行分组。任何建议。

例如,我有一个数组 var a = [10, 100, 20, 50, 20, 50, 70, 120]

我的最大长度为150,最小长度为3,即每个子数组的最大总和为150,最大长度为3

任何建议使它像这样[[10, 100, 20], [50, 20, 50], [70], [120]]

提前致谢

【问题讨论】:

    标签: javascript arrays underscore.js lodash


    【解决方案1】:

    在这里,groupArray 函数将迭代您的输入并根据提供的最大长度和最大总和构建组。

    function groupArray(input, maxSum, maxLen) {
      const res = [[]];
      let mark = 0;
      let sum = 0;
    
      input.forEach( ele => {  
        // if the current group has already reach maxLenght or maxSum
        // then create a new group
        if ( res[mark].length > (maxLen-1)
            || (sum + ele) > maxSum ) {
          res.push([ele]);
          mark++;
          sum = ele;
        }
        // otherwise add to current grop
        else {
          res[mark].push(ele);
          sum += ele;
        }
      });
      return res;
    }
    
    const test_1 = [10, 100, 20, 50, 20, 50, 70, 120];
    const test_2 = [10, 130, 20, 50, 20, 50, 70, 120];
    const test_3 = [140, 110, 20, 50, 20, 50, 70, 120];
    
    console.log(groupArray(test_1, 150, 3));
    console.log(groupArray(test_2, 150, 3));
    console.log(groupArray(test_3, 150, 3));

    注意:由于该问题没有任何附加规则,因此此函数不会重新排序数组或尝试寻找最佳可能的长度匹配或最佳可能的和匹配。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-24
      • 2010-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多