We have a numerical array with arbitrary max values for each element. How do we increment the elements so the array would go from [0, 0, 0]
to [x, y, z]
?
To illustrate if the max array is [2, 1, 2]
and we start the main array at [0, 0, 0]
incrementing should take the main array through these steps:
[0, 0, 0]
[1, 0, 0]
[2, 0, 0]
[0, 1, 0]
[1, 1, 0]
[2, 1, 0]
[0, 0, 1]
[1, 0, 1]
[2, 0, 1]
[0, 1, 1]
[1, 1, 1]
[2, 1, 1]
[0, 0, 2]
[1, 0, 2]
[2, 0, 2]
[0, 1, 2]
[1, 1, 2]
[2, 1, 2]
I have written a function which stops incrementing as soon as it reaches a max of 1. Here is my code:
var maxes = [2, 1, 2];
var myArray = [0, 0, 0];
function step() {
for(var i = 0; i < myArray.length; i++) {
if(myArray[i] == maxes[i]) {
continue;
} else {
myArray[i] = myArray[i] + 1;
return;
}
}
return false;
}
for(j = 0; j < 100; j++) {
result = step();
if(!result) break;
console.log(result);
}