Last active
February 7, 2017 00:55
-
-
Save fitzk/4f8a7a9169bbc13587c8d240f290afe5 to your computer and use it in GitHub Desktop.
Find all permutations of a string using recursion.
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 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