It seems that using functions such as .push, .pop, .shift, .unshift and .splice on a copy of an array will modify the original as well and I don’t understand why. This tends to thwart efforts to move data around without changing the original input around. In particular, my solution to “No repeats please” did not work until I added lines 28 and 29 to return the 2 element array to its original order.
function permAlone(str) {
if (str.length === 0) {
return 0;
} else if (str.length === 1 ) {
return 1;
} else if (str.length === 2) {
if (str[0] == str[1]) {
return 0;
} else {
return 2;
}
}
var strArr = str.split("");
function permute(stringArray) {
if (stringArray.length == 2) {
var tempStrArr = stringArray;
var stringPermutationArray = [tempStrArr.join("")];
var tempChar = tempStrArr.shift();
tempStrArr.push(tempChar);
stringPermutationArray.push(tempStrArr.join(""));
tempChar = tempStrArr.shift(); // line 28
tempStrArr.push(tempChar); // line 29
return stringPermutationArray;
} else {
var altTempChar = "";
var altStringPermutationArray = [];
var altTempStrArr = stringArray;
for (var k=0; k < altTempStrArr.length; k++) {
altTempChar = altTempStrArr.splice(k,1)[0];
var tempPermArr = permute(altTempStrArr);
for (var m = 0; m < tempPermArr.length; m++) {
tempPermArr[m] = altTempChar + tempPermArr[m];
}
altStringPermutationArray = altStringPermutationArray.concat(tempPermArr);
altTempStrArr.splice(k, 0, altTempChar);
}
return altStringPermutationArray;
}
}
var strPermArr = permute(strArr);
var permCount = strPermArr.length;
for (var n=0; n < strPermArr.length; n++) {
if (/([A-Za-z])\1{1,}/.test(strPermArr[n])) {
permCount–;
}
}
return permCount;
}