I have array [1,2,3,4]
I want to print all combinations like:
[1]
[2]
[3]
[4]
[1,2]
[1,2,3]
[1,2,3,4]
[2,3]
[2,3,4]
[3,4]
[1,3]
[1,3,4]
[1,4]
[2,4]
How I can do that?
I have array [1,2,3,4]
I want to print all combinations like:
[1]
[2]
[3]
[4]
[1,2]
[1,2,3]
[1,2,3,4]
[2,3]
[2,3,4]
[3,4]
[1,3]
[1,3,4]
[1,4]
[2,4]
How I can do that?
This is simple to do recursively:
function printCombinations(arr, prefix) {
if (arr.length == 0) {
if (prefix.length > 0) {
console.log(prefix);
}
return;
}
prefix = prefix || [];
printCombinations(arr.slice(1), prefix.concat(arr[0]));
printCombinations(arr.slice(1), prefix);
}
printCombinations([1, 2, 3, 4]);