/*比如有这样一个数组,数组只相加<=8分组,大于8就分到下一组,
结果如下应该是一个二维数组:*/
var arr = [2, 3, 4, 2, 2, 2, 3, 4];
arr= [
[2,3],
[4,2,2],
[2,3],
[4]
]
伪代码:
function fuck(arr)
{
newArray = [[]];
foreach(a in arr):
{
if(sum(newArray.Last) + a <= 8)
{
newArray.Last.append(a);
}
else
{
nextArray = [a];
newArray.append(nextArray)
}
}
return newArray;
}
我按照思路自己调试下,3q
function fuck(arr) {
var newArray = [[]];
//sum函数
function sum(arr) {
arr = arr || [];
var total = arr.reduce(function (total, item) {
return total + item;
}, 0);
return total;
}
arr.forEach(a => {
//变动
newArray.Last = newArray.Last || [];
if (sum(newArray.Last) + a <= 8) {
newArray.Last.push(a);
}
else {
var nextArray = [a];
newArray.push(nextArray)
}
});
return newArray;
}
var a = fuck(arr);
console.info(a);
改下后没有达到预期效果
@困了: 大哥,我写的是伪代码,因为我 不熟悉js,给你修改下:
function fuck(arr) {
var newArray = [[]];
//sum函数
function sum(arr) {
arr = arr || [];
var total = arr.reduce(function (total, item) {
return total + item;
}, 0);
return total;
}
arr.forEach(a => {
//变动
newArray[newArray.length - 1] = newArray[newArray.length - 1] || [];
if (sum(newArray[newArray.length - 1]) + a <= 8) {
newArray[newArray.length - 1].push(a);
}
else {
var nextArray = [a];
newArray.push(nextArray)
}
});
return newArray;
}
var arr = [2, 3, 4, 2, 2, 2, 3, 4];
var a = fuck(arr);
js的数组好像没有Last属性,改改就能用了
@会长: 刚才last那个没想明白