Skip to content

Instantly share code, notes, and snippets.

@alexislagante
Created November 7, 2015 10:05
Show Gist options
  • Save alexislagante/a4c8b53a50e34695eb98 to your computer and use it in GitHub Desktop.
Save alexislagante/a4c8b53a50e34695eb98 to your computer and use it in GitHub Desktop.
Generate all possible permutations of a string
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