将数组数组拆分为总和小于或等于给定数字的数组

时间:2013-08-04 15:04:16

标签: javascript jquery arrays algorithm

如果数组是:[1,2,3,4,5,6,7,8,9,10]
和最大金额是25
脚本应该创建三个数组
arr1:[1,2,3,4,5,6](总和= 21)
arr2:[7,8,9](总和= 24)
arr3:[9,10](总和= 19)
我可以创建第一个阵列而不是其他阵列,有人可以帮助我吗?

我的jquery代码是:

$(document).ready(function(){
  numbers=[1,2,3,4,5,6,7,8,9,10]
  total = 0;
  newOne =[];
  for(i = 0; i < numbers.length; i++) {
       if(total<= (25-numbers[i])){
        total += numbers[i];
        newOne.push(numbers[i]);
       };
    };
  numbers.splice(0,newOne.length);
  console.log(newOne);  
  console.log(numbers);     
});

感谢所有

2 个答案:

答案 0 :(得分:1)

也许有点简单:

$(document).ready(function(){
  var numbers=[1,2,3,4,5,6,7,8,9,10]
  var total;
  var newOne = [];
  var index = -1;
  while (numbers.length) {
    total = 0;
    index++;
    newOne[index] = []
    while (total + numbers[0] <= 25 ) {
      total += numbers[0];
      newOne[index].push(numbers.shift());
    }
  }  
  console.log(newOne);  
  console.log(numbers);     
});

答案 1 :(得分:0)

这样的东西
$(document).ready(function(){
    numbers = [1,2,3,4,5,6,7,8,9,10];
    total = 0;
    coll = [];
    newOne = null;
    for (i = 0; i < numbers.length; i++) {
        if (newOne !== null && total + numbers[i] <= 25) {
            total += numbers[i];
            newOne.push(numbers[i]);
        } else {
            // We enter in the else for i = 0 and when we have to
            // create a new subarray
            if (newOne !== null)
            {
                console.log(newOne);
            }

            total = numbers[i];
            newOne = [ numbers[i] ];
            coll.push(newOne);
        }
    }

    // We have to print the last subarray (because normally
    // a subarray is printed only when it's filled)
    console.log(newOne);     
}

我没有拼接原始数组。我甚至将所有各种子阵列放入coll

如果您只想在最后打印数组:

numbers = [1,2,3,4,5,6,7,8,9,10];
total = 0;
coll = [];
newOne = null;
for (i = 0; i < numbers.length; i++) {
    if (newOne !== null && total + numbers[i] <= 25) {
        total += numbers[i];
        newOne.push(numbers[i]);
    } else {
        total = numbers[i];
        newOne = [ numbers[i] ];
        coll.push(newOne);
    }
}

// Here we print the subarrays
for (i = 0; i < coll.length; i++)
{
    console.log(coll[i]);
}