I'm currently working on a problem that requires me to get a certain number with a given 3d array. That Array Contains 2D arrays which contain a number x amount of time. Parent array sorted from bigger to smaller.
Example of parent array;
array = [
[5, 5, 5, 5, 5, 5],
[4, 4, 4],
[3, 3, 3, 3],
[1, 1, 1, 1, 1, 1, 1],
];
and number I want to get is 27;
let number = 0;
for (let i = 0; i < array.length; i++){
for (let j = 0; j < array[i].length; j++){
number += array[i][j]
}
}
The for loop above is obviously sums every number in the parent array but I want it to skip the loop when the number passes the 27 and finally break when it is 27.
For the example above, in the first loop, it should run until the number is 25 and skip to the second loop; the second and third loops skip because the number needs to be equal to 27; and finally, the loop breaks in the second run of the fourth loop when the number is 27;
I'm sorry for this long-ass and bloated explanation, my js knowledge is limited I have to try to explain it in words.
var target = 27; // Or whatever
let number = 0;
let helpers = []
for (let i = 0; number < target && i < array.length; i++){
helper = []
for (let j = 0; number < target && j < array[i].length; j++){
if ( number + array[i][j] <= target ) {
helper.push(array[i][j])
if ( ( number += array[i][j] ) == target ) {
helpers.push(helper)
helper = []
console.log( `Found target ${target} at i=${i}, j=${j}` );
break;
}
}
}
if (helper.length) {
helpers.push(helper)
}
}
console.log(helpers)