Created
November 7, 2015 10:05
-
-
Save alexislagante/a4c8b53a50e34695eb98 to your computer and use it in GitHub Desktop.
Generate all possible permutations of a 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 permutation(str, cache) { | |
var chars = str.split(""); | |
if (chars.length == 1) { | |
return chars; | |
} | |
cache = cache || {}; | |
if(cache[str]) { | |
return cache[str]; | |
} | |
result = chars.reduce(function(res, curr, idx, array){ | |
var subStr = str.slice(0,idx)+str.slice(idx+1); | |
var subResult = permutation(subStr, cache); | |
subResult.forEach(function(v){ | |
res.push(curr+v); | |
}); | |
return res; | |
}, []); | |
cache[str] = result; | |
return result; | |
} | |
permutation("abcdefg"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment