Hi all, I’m having some trouble with this challenge. Here’s my code:
function permAlone(str) {
var arr = str.split("");
var numArr = [];
var permArr = [];
var permutation = 1;
arr.forEach(function(value, index) {
permutation = permutation * (index+1);
numArr.push(index+1);
});
var reString = numArr.join("");
var first = numArr[0];
var last = numArr[numArr.length-1];
var re = new RegExp("^" + ("[" + first + "-" + last + "]").repeat(numArr.length) + "$","g");
var num = reString * numArr.length;
function hasRepeatedNumbers(repeatNum) {
repeatNum = repeatNum.toString().split("").sort().join("");
var patt = new RegExp(/([0-9])\1+/,"g");
var result = patt.test(repeatNum);
return result;
}
var x = num;
while (x > 0) {
if (re.test(x) && !(hasRepeatedNumbers(x))) {
permArr.push(x);
}
x--;
}
return permArr;
}
permAlone('aabb');
I attempted to switch up the strings into numbers and then find all permutations of those numbers. Currently my loop only pushes 13 numbers into my array. I can’t seem to understand why it’s not recognizing the other 3. Any help would be greatly appreciate.
It looks like the issue has to do with Regular expression test() method, but I haven’t figured the real reason yet and how test() really actually works…, I went on MDN and found this mysterious excerpt (hopefully you will help me understand) :
As with exec() (or in combination with it), test() called multiple times on the same global regular expression instance will advance past the previous match.
So, I changed one line.
function permAlone(str) {
var arr = str.split("");
var numArr = [];
var permArr = [];
var permutation = 1;
arr.forEach(function(value, index) {
permutation = permutation * (index+1);
numArr.push(index+1);
});
var reString = numArr.join("");
var first = numArr[0];
var last = numArr[numArr.length-1];
// var re = new RegExp("^" + ("[" + first + "-" + last + "]").repeat(numArr.length) + "$","g");
var num = reString * numArr.length;
function hasRepeatedNumbers(repeatNum) {
repeatNum = repeatNum.toString().split("").sort().join("");
var patt = new RegExp(/([0-9])\1+/,"g");
var result = patt.test(repeatNum);
return result;
}
var x = num;
while (x > 0) {
if (new RegExp("^" + ("[" + first + "-" + last + "]").repeat(numArr.length) + "$","g").test(x) // replaced "re" with a newly created RegExp
&& !(hasRepeatedNumbers(x))) {
permArr.push(x);
}
x--;
}
return permArr;
}
permAlone('aabb');