Created
November 7, 2015 08:10
-
-
Save alexislagante/0eecd41e57b859bbd0ce to your computer and use it in GitHub Desktop.
Get all possible combinations with length n of string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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