Answer the question
In order to leave comments, you need to log in
How to make combination of elements of different arrays avoiding nested for loops?
The question is. You need to combine arrays
Option 1
group1 = 1,2,3
group2 = 1,2,3
The output should be 11, 12, 13, 21, 22, 23, 31,32,33
Option 2
group1 = 1,2,3
group2 = 1,2,3
group3 = 1,2,3
The output should be
111, "112", "113", "121", "122", "123", "131", "132", "133", "211", "212", "213", "221", "222", "223", "231", "232", "233", "311", "312", "313", "321" ", "322", "323", "331", "332", "333"
var group1=["1","2","3"];
var group2=["1","2","3"];
var group3=["1","2","3"];
var firstDigit = "";
var secondDigit = "";
var thirdDigit = "";
var pusher = "";
var variants = [];
for(a=0; a<group1.length;a++){
firstDigit = group1[a];
for(b=0;b<group2.length;b++){
secondDigit = group2[b];
for(c=0; c<group3.length; c++){
thirdDigit = group3[c];
pusher = firstDigit + secondDigit + thirdDigit;
variants.push(pusher);
}
}
}
Answer the question
In order to leave comments, you need to log in
0. Have B - an array of arrays of options.
1. Create P - an array of current positions in each array (initializing them all with zero).
2. Save (or display) the current combination - for(i) B[ i ][ P[ i ] ]
3. Loop through P from 0 to the end, find a position that can be increased, reset all that are before it.
4. If you managed to do it, go back to step 2.
This way you get no more than one nested loop.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question