I'm working on a JavaScript function that will generate permutations of a nested array (let's call it input). I want to do it in a way, that the length of permutations will be of input.length. So, given
var input = [["0", "5", "9"], ["2", "3"], ["0", "5", "4"]];
I'm looking to generate permutations of length 3, containing any of ["0", "5", "9"] as a first character, any of ["2", "3"] as the second character etc.
My main challenge is I don't understand recursion well enough to apply it to the problem at hand. I understand the general principle and can step through a given function in order to understand how it behaves (obviously, the more complex the function is, the longer it takes me to understand it. When I can't wrap my mind around a function, I use sticky notes and map each call using a separate note on my wall. This way I can easier visualize the pattern and usually after stepping through a couple of calls my understanding becomes much better). However, if I were to write the same function that I'm able to understand that way, I would probably struggle.
So I've found a function that generates permutation of a simple string with an intention to modify it in a way so that it handles a nested array and generates desired output.
var permutations = [];
function doPerm(str, arr) {
if (typeof (str) == 'string') str = str.split('');
if (str.length == 0) permutations.push(arr.join(''));
for (var i = 0; i < str.length; i++) {
var x = str.splice(i, 1);
arr.push(x);
doPerm(str, arr);
arr.pop();
str.splice(i, 0, x);
}
}
A modification would add another level on top of the existing function (as from what I imagine "rest" variable would have to be a permutation itself).
However, I'm sure there's a way to simplify the problem. Any guidance or possible solutions to this will be appreciated.
input = [["3, "4"], ["8", "9"], ["5", "6"]];I want the function to generateoutput = ["385", "386", "395", "396", "485", "486", "495", "496"];Thanks!