var Combination = [];
function Reduce(List, Target) {
if(List.length > 1) {
return Reduce(List.filter(word => word !== List[0]), List[1]);
} else {
return List[0];
}
}
If user input X = ["AB, "DE", "SZ", "YY"]
, above function have to return all possible combination like ["AB", "DE"], ["AB", "YY", "SZ"]
.
I’m trying to solve it in recursive way, but stuck at pushing result to Combination
.
Where do I have to change to get all possible combinations?
If my approach is wrong, thanks for the correction in advance🙏🏻
3
Answers
It looks like you’re looking for the power set of your inputs, that is, the set of all subsets of your set. For instance, the power set of
[1, 2, 3]
is:This includes the first, empty array, and every other combination of the elements. There will be
2 ^ n
elements in the set, wheren
is the length of your original set. Note that although this is an array, it is theoretically an unordered collection.Here is one version of
powerSet
:(We add the
.join('/')
just to make it easier to see on the console. The result is an array of arrays.)We recur on the tail of the array, keeping those values as well as the sets found by including the head of the array alongside the values of that subset.
What you describe are all permutations of all subsets of an n-set.
One way to produce those is to use a generator function:
You could write this in a recursive manner, but it would be more complicated and would create way more throwaway arrays in the process.
Another approach that is a bit more academic. Think numbers in binary, and each position tells if this item is included in this particular combination.
That means for
n
items in the list you need to go up to combination(2 ** n)-1
which is justn
ones.So you count up and check the bits which items of the
list
it contains.