Skip to content

Instantly share code, notes, and snippets.

@BetterProgramming
Created June 30, 2020 14: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 BetterProgramming/d895d3aef2c6ffba83c2a613124c8679 to your computer and use it in GitHub Desktop.
Save BetterProgramming/d895d3aef2c6ffba83c2a613124c8679 to your computer and use it in GitHub Desktop.
function permutations(str) {
let arr = []
// base case: less than 2 characters in the string
if (str.length < 2) {
arr.push(str)
return arr
}
for (let i = 0; i < str.length; i++) {
let currentChar = str[i]
let remainingStr = str.slice(0, i) + str.slice(i + 1, str.length)
let remainingPermutation = permutations(remainingStr) // save the result of the recursive function
// if we find a repeating character, don't add it to the arr
if (str.indexOf(currentChar) !== i) {
continue
}
// concat currentChar with each substring and push to the arr
remainingPermutation.forEach(subString => arr.push(currentChar + subString))
}
return arr
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment