Reputation: 1566
If array is: [1,2,3,4,5,6,7,8,9,10]
and max-sum is 25
The script should create three arrays
arr1:[1, 2, 3, 4, 5, 6] (sum=21)
arr2:[7,8,9] (sum=24)
arr3:[9,10] (sum=19)
I can create the first array but not the others, someone could kindly help me?
My jquery code is:
$(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);
});
Thanks to all
Upvotes: 0
Views: 1344
Reputation:
Perhaps a little simpler:
$(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);
});
Upvotes: 1
Reputation: 111860
Something like
$(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);
}
I don't splice the original array. I even put in coll
all the various sub-arrays.
If you only want to print the array at the end:
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]);
}
Upvotes: 0