Skip to content

Instantly share code, notes, and snippets.

@fitzk
Last active February 7, 2017 00:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fitzk/4f8a7a9169bbc13587c8d240f290afe5 to your computer and use it in GitHub Desktop.
Save fitzk/4f8a7a9169bbc13587c8d240f290afe5 to your computer and use it in GitHub Desktop.
Find all permutations of a string using recursion.
function getPermutations(string, p) {
if(string.length <= 1) return new Set(string)
let allCharsExceptLast = string.slice(0, -1)
let lastChar = string[string.length - 1]
let permutationsOfAllCharsExceptLast = getPermutations(allCharsExceptLast);
let permutations = new Set()
for(let perm of permutationsOfAllCharsExceptLast) {
for(let position=0; position <= allCharsExceptLast.length; position++) {
let permutation = perm.slice(0, position) + lastChar + perm.slice(position)
permutations.add(permutation)
}
}
return permutations
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment