Created
June 30, 2020 14:55
-
-
Save BetterProgramming/d895d3aef2c6ffba83c2a613124c8679 to your computer and use it in GitHub Desktop.
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 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