I have come up with the following code for this challenge. The problem is it works with some cases while not with some other! And I can’t seem to get why it’s not working there. So can somebody look into it?
PS:
-
It works with
permAlone("aab")
,permAlone("aaa")
,permAlone("aabb")
,permAlone("zzzzzzzz")
,permAlone("aaab")
,permAlone("a")
-
It doesn’t work with
permAlone("aaabb")
,permAlone("abcdefa")
,permAlone("abfdefa")
-
console.log
statements will help you to follow the flow of the program.
function swap(arr, x, y) {
var temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
return arr;
}
function factorial(n) {
var facto = 1;
for (var k = 1; k <= n; k++) {
facto = facto * k;
}
return facto;
}
function permAlone(str) {
var charArr = str.split("");
console.log(charArr);
var n = charArr.length;
var f = factorial(n);
console.log("f="+f);
var permArr = [];
if(n == 1) {
return 1;
} else {
for (var i = 0; i < f/(n-1); i++) {
for (var j = 0; j < n-1; j++) {
charArr = swap(charArr, j, j+1);
//console.log(charArr);
//permArr.push(charArr);
permArr += charArr + ";" ;
permArr = permArr.replace(/,/g,'');
console.log(permArr);
}
}
permArr = permArr.slice(0,-1).split(";");
console.log(permArr);
var count = 0;
for (var m=0; m < permArr.length; m++) {
if(/([a-z])\1{1,}/.test(permArr[m]) === false) {
count++;
}
}
return count;
}
}
permAlone('aaabb');