Created
April 15, 2018 14:55
-
-
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…
This file contains 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 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