Created
February 23, 2015 03:48
-
-
Save graemeboy/6ea360f2630892e47452 to your computer and use it in GitHub Desktop.
String Permutations
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 combineChars (chars) { | |
| var permutations = [], words = [], firstChar; | |
| if (chars.length === 1) { // base case | |
| permutations.push(chars); | |
| return permutations; | |
| } | |
| firstChar = chars[0]; | |
| chars = chars.substring(1,chars.length); | |
| words = combineChars(chars); | |
| for (var i = 0; i < words.length; i++) { | |
| for (var j = 0; j < words[i].length + 1; j++) { | |
| permutations.push(insertCharAt(words[i], firstChar, j)); | |
| } | |
| } | |
| return permutations; | |
| } | |
| function insertCharAt(word, charIn, i) { | |
| var start = word.substring(0,i); | |
| var end = word.substring(i,word.length); | |
| return start + charIn + end; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment