基于最大值和长度的组数组

问题描述 投票:-1回答:1

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

例如,我有一个数组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个回答
0
投票
在这里,groupArray函数将在您的输入上进行迭代,并根据提供的最大长度和最大和建立组。

const calcSum = arr => arr.reduce((s,i) => s+i,0); function groupArray(input, maxSum, maxLen) { const res = [[]]; let mark = 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) || (calcSum(res[mark]) + ele) > maxSum ) { res.push([ele]); mark++; } // otherwise add to current grop else { res[mark].push(ele); } }); return res; } const input = [10, 100, 20, 50, 20, 50, 70, 120]; console.log(groupArray(input, 150, 3));
注意:由于问题没有任何其他规则,因此该函数不会对数组重新排序,也不会尝试寻找最佳的长度匹配或最佳的总和匹配。
© www.soinside.com 2019 - 2024. All rights reserved.