get all combinations for a string
This is a recursive solution that I think is very easy to understand.
var tree = function(leafs) {
var branches = [];
if (leafs.length == 1) return leafs;
for (var k in leafs) {
var leaf = leafs[k];
tree(leafs.join('').replace(leaf, '').split('')).concat("").map(function(subtree) {
branches.push([leaf].concat(subtree));
});
}
return branches;
};
console.log(tree("abc".split('')).map(function(str) {
return str.join('')
}))
You could use a nasty trick and increase a counter and use its binary representation as flags:
function combine(str){
const result = [];
for(let i = 1; i < Math.pow(2, str.length) - 1; i++)
result.push([...str].filter((_, pos) => (i >> pos) & 1).join(""));
return result;
}
Try it
This is what I ended up using.
var combinations = function (string)
{
var result = [];
var loop = function (start,depth,prefix)
{
for(var i=start; i<string.length; i++)
{
var next = prefix+string[i];
if (depth > 0)
loop(i+1,depth-1,next);
else
result.push(next);
}
}
for(var i=0; i<string.length; i++)
{
loop(0,i,'');
}
return result;
}