Created
May 2, 2018 16:59
-
-
Save danedavid/cb5db5a77f37ef1f1021057a51d240b2 to your computer and use it in GitHub Desktop.
Permutations of a String in JavaScript
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
| // returns an array containing all permutations of a given string | |
| const permute = str => { | |
| let permutations = []; | |
| if ( str.length <= 1 ) { | |
| return [str]; | |
| } | |
| for ( let i = 0; i < str.length; i++ ) { | |
| let char = str[i]; | |
| // if more than one occurence of the character | |
| if ( str.indexOf(char) !== i ) { | |
| continue; | |
| } | |
| let restOfString = str.slice(0, i) + str.slice(i + 1); | |
| permute(restOfString).forEach(item => { | |
| permutations.push(char + item); | |
| }); | |
| } | |
| return permutations; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment