Skip to content

Instantly share code, notes, and snippets.

@nickihastings
Created April 15, 2018 14:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickihastings/82334a570b5737057d4c29d3f10e2e7f to your computer and use it in GitHub Desktop.
Save nickihastings/82334a570b5737057d4c29d3f10e2e7f to your computer and use it in GitHub Desktop.
Return the number of total permutations of the provided string that don't have repeated consecutive letters. Assume that all characters in the provided string are each unique. For example, aab should return 2 because it has 6 total permutations (aab, aab, aba, aba, baa, baa), but only 2 of them (aba and aba) don't have the same letter (in this c…
function permAlone(str) {
//check if the string provided is only one character
if(str.length === 1){
return 1;
}
//function to create the permutations
//for each value in the string, add the permutations of the rest
function getPermutations(str){
var output = [];
//to test for doubles, between brackets capture any letter then match it again,
//the '1' indicates captured group 1 (similar to $1)
var regex = /([a-z])\1/i;
//check the length of the string, if it's one return it to build the new string
if(str.length === 1){
return str;
}
//for every first letter... (recursion function)
for(var i = 0; i<str.length; i++){
//make a copy of the string less one character
var tempStr = str.substring(0, i) + str.substring(i+1);
var char = str[i]; //hold the first letter
//recall the function with the smaller string
var permutations = getPermutations(tempStr);
//loop through the new permutations and add the first character to each.
for(var j = 0; j<permutations.length; j++){
//check new string against regex and only add those with no doubles
if(!regex.test(char + permutations[j]) ){
output.push(char + permutations[j]);
}
}
}
return output;
}
//call the permutations function for the string provided
var permutes = getPermutations(str);
//return the number of permutations without doubles
return permutes.length;
}
permAlone('aab');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment