Created
July 30, 2019 05:15
-
-
Save porteron/0939289d1c60467d6fc13d6cb87bebc0 to your computer and use it in GitHub Desktop.
Find all permutations of a string.
This file contains hidden or 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(word){ | |
| if(word.length <=1) return [word]; | |
| if(typeof word === 'string'){ | |
| word = word.split('') | |
| } | |
| if(typeof word === 'number'){ | |
| word = String(word).split('') | |
| } | |
| let permutationCollection = []; | |
| let nextWord = []; | |
| let characters = []; | |
| permute(word); | |
| return permutationCollection | |
| function permute(characters){ | |
| if(characters.length < 1){ | |
| // add word to permutations array | |
| permutationCollection.push(nextWord.join('')); | |
| } | |
| for(let i = 0; i < characters.length; i++){ | |
| characters.push(characters.shift()); | |
| nextWord.push(characters[0]) | |
| permute(characters.slice(1);); | |
| nextWord.pop(); | |
| } | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Find all permutations of a string
Steps: