如果数组是:[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);
});
感谢大家
最佳答案
也许更简单一些:
$(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);
});
关于javascript - 将数字数组拆分为总和小于或等于给定数字的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18044338/