0

如果数组是:[1,2,3,4,5,6,7,8,9,10]
并且 max-sum 是 25
脚本应该创建三个数组
arr1:[1, 2, 3, 4, 5, 6] (sum=21)
arr2:[7,8,9] (sum=24)
arr3:[9,10] (sum=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);     
});

谢谢大家

4

2 回答 2

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);     
});
于 2013-08-04T15:34:04.383 回答
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]);
}
于 2013-08-04T15:19:20.003 回答