Created
May 31, 2017 06:05
-
-
Save khalid32/41443e7ed160b95b167d3702f206c969 to your computer and use it in GitHub Desktop.
Freecodecamp's Advanced Algorithm Scripting Challenge
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
/* | |
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 case a) repeating. | |
*/ | |
function permAlone(str) { | |
var regex = /(.)\1+/g; | |
var arr = str.split(''), permutations = [], temp; | |
if (str.match(regex) !== null && str.match(regex)[0] === str) return 0; | |
function swap(a, b) { | |
temp = arr[a]; | |
arr[a] = arr[b]; | |
arr[b] = temp; | |
} | |
function generate(int) { | |
if (int === 1) { | |
permutations.push(arr.join('')); | |
} else { | |
for (var i = 0; i != int; ++i) { | |
generate(int - 1); | |
swap(int % 2 ? 0 : i, int - 1); | |
} | |
} | |
} | |
generate(arr.length); | |
var filtered = permutations.filter(function(string) { | |
return !string.match(regex); | |
}); | |
return filtered.length; | |
} | |
permAlone('aab'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment