Skip to content

Instantly share code, notes, and snippets.

@aldraco
Last active August 29, 2015 14:16
Show Gist options
  • Save aldraco/e26ea4cffe7e7fcc1a75 to your computer and use it in GitHub Desktop.
Save aldraco/e26ea4cffe7e7fcc1a75 to your computer and use it in GitHub Desktop.
permutations code found on the internet for bonfire challenge
function permAlone(str) {
var permArr = [], usedChars = [];
function permute(input) {
//convert input into a char array (one element for each character)
var i, ch, chars = input.split("");
for (i = 0; i < chars.length; i++) {
//get and remove character at index "i" from char array
ch = chars.splice(i, 1);
//add removed character to the end of used characters
usedChars.push(ch);
//when there are no more characters left in char array to add, add used chars to list of permutations
if (chars.length == 0) permArr[permArr.length] = usedChars.join("");
//send characters (minus the removed one from above) from char array to be permuted
permute(chars.join(""));
//add removed character back into char array in original position
chars.splice(i, 0, ch);
//remove the last character used off the end of used characters array
usedChars.pop();
}
return permArr;
}
permArr = permute(str);
// filter out duplicates from permArr
permArr = permArr.filter(function(perm, index) {
perm = perm.split('');
return perm.every(function(letter, index) {
if (index === perm.length-1) {
return true;
}
return (letter !== perm[index+1]);
});
});
return permArr.length;
}
permAlone('baa');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment