2

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!

  • 1
    No, this is not the permutations, this is called cartesian product. – Bergi Apr 08 '20 at 18:42
  • 1
    Your approach is totally correct. The only thing i can see missing is a `var` declaration for `i`, which would make the variable local to the call - currently it is a global variable, shared across all your recursive calls, which destroys the looping. Make sure to use strict mode, it would have caught this mistake. – Bergi Apr 08 '20 at 18:44
  • 1
    Thank you so much! I was initially convinced it was a problem with scope, but just couldn't spot it however long I stared. – user3623992 Apr 08 '20 at 18:56

0 Answers0