Skip to content

Instantly share code, notes, and snippets.

@graemeboy
Created February 23, 2015 03:48
Show Gist options
  • Select an option

  • Save graemeboy/6ea360f2630892e47452 to your computer and use it in GitHub Desktop.

Select an option

Save graemeboy/6ea360f2630892e47452 to your computer and use it in GitHub Desktop.
String Permutations
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