Skip to content

Instantly share code, notes, and snippets.

@alexislagante
Created November 7, 2015 08:10
Show Gist options
  • Save alexislagante/0eecd41e57b859bbd0ce to your computer and use it in GitHub Desktop.
Save alexislagante/0eecd41e57b859bbd0ce to your computer and use it in GitHub Desktop.
Get all possible combinations with length n of string
function combination(str, n) {
var chars = str.split("");
n = Math.min(chars.length, n);
var result = [[]];
for (var i=0; i<n; i++) {
var newResult = [];
result.forEach(function(item) {
var lastIndex = -1;
if (item.length>0){
lastIndex = item[item.length-1];
}
var startIndex = lastIndex+1;
for (var j=startIndex;j<chars.length-n+1+i;j++) {
newResult.push(item.concat(j))
}
});
result = newResult;
}
return result.map(function(item){
return item.map(function(index){
return chars[index];
}).join("");
});
}
combination("alexislagante",3);
combination("abcdefghijklmnopqrstuvwxyz",5);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment