Let's say I have the following array of arrays:
A = [
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h'],
['i'],
['j', 'k', 'l']
]
I want to find all possible combinations of the elements of each array with the elements of the other arrays (i.e. 'adgij' is one possibility but not 'abcde').
I can brute force it and just loop everything like this (javascript):
var A = [
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h'],
['i'],
['j', 'k', 'l']
],
combinations,
newCombinations = [];
A.forEach(function(a, index) {
newCombinations = [];
if (index === 0) {
newCombinations = a;
} else {
a.forEach(function(val){
combinations.forEach(function(combination){
newCombinations.push(combination + val);
});
});
}
combinations = newCombinations;
});
The problem with this method is that it is breadth-first, so if I want to stop after n iterations I would have incomplete combinations.
Is there a way to get all possible combinations using depth-first method?