I have an array as follows:
charSet = [
["A", "B"],
["C", "D", "E"],
["F", "G", "H", "I"]
];
I want to print all the permutations with the elements from charSet[0] in the first column, those from charSet[1] in the second, etc:
ACF, ACG, ACH, ACI, ADF, ADG, ... BEI
the function must be able to take an arbitrary number of columns, and an arbitrary number of possible characters in each. So, recursion needed. Unfortunately, my brain doesn't seem to be capable of processing recursion. I thought by writing an inflexible solution as a set of nested for loops, it might help to make the recursive solution clearer:
for(i=0; i<charSet[0].length; i++){
a[0] = charSet[0][i];
for(j=0; j<charSet[1].length; j++){
a[1] = charSet[1][j];
for(k=0; k<charSet[2].length; k++){
a[2] = charSet[2][k];
console.log(a.join(''));
}
}
}
8 hours and many failed attempts later, I've concluded that it did not help. So far my best effort has been:
function printOutput(len) {
if(len==0){
console.log(a.join(''));
return;
}
for(i = 0; i<charSet[len-1].length; i++){
a[len-1] = charSet[len-1][i];
printOutput(len-1);
}
}
printOutput(charSet.length);
I can see why it doesn't work, but I'm not getting any closer to working out what will. Please help!