# No repeats please - issue with heap's algorithm

Tell us what’s happening:
I get correct answers except for “abcdefa”, “abfdefa”, and “aaabb”. I’m using heap’s algorithm for this. Just don’t see where my mistake is, any help is much appreciated.

``````
var len = str.length;

var p = [];
var chars = str.split('');
var length = chars.length;
var total = 0;
var temp;
var r = /(.)\1+/g;

function buildPerms(n, arr){
var copyArr = arr.slice(0);

if(n == 1){
console.log(copyArr);
p.push(copyArr);
}
for(var i = 0; i !== n; i++){
buildPerms((n-1), copyArr);
if(n%2 == 0){
temp = copyArr[0];
copyArr[0] = copyArr[n-1];
copyArr[n-1] = temp;
}
else{
temp = copyArr[i];
copyArr[i] = copyArr[n-1];
copyArr[n-1] = temp;
}
}
}

buildPerms(len, chars);

var newArr = [];

for(var x = 0; x < p.length; x++){
temp = p[x].join('');
newArr.push(temp);
}

var f = newArr.filter(function(elem, ind){
console.log(elem);
return !elem.match(r);
});

return f.length;
}

permAlone("aabb");
``````

Your Browser User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36`.

In Heap’s Algorithm, you don’t need to make a copy of the input array. Also, when pushing an array (a) into another array (b), it results in pushing the array (b) in by reference, and not by value (so you would see the same pushed array (b) in the holding array (a)). Instead, you can push in the string of the array values by using the `.join()` method. I haven’t gotten a working regex, so here’s what I have so far and it works:

``````function permAlone(str) {
var len = str.length;

var p = [];
var chars = str.split('');
// var length = chars.length; // not needed (remove line)
// var total = 0; // not needed (remove line)
var temp;
// var r = /(.)\1+/g; // regex not showing correct number (not used)

function buildPerms(n, arr){
var copyArr = arr;

if (n == 1) {
// console.log(copyArr);
p.push(copyArr.join('')); // pushes the string result of the array in by value
// p.push(copyArr); NO! pushing just copyArr in results in doing it by reference, not by value
}
for (var i = 0; i !== n; i++) {
buildPerms((n - 1), copyArr);
if (n % 2 == 0) {
temp = copyArr[0];
copyArr[0] = copyArr[n - 1];
copyArr[n - 1] = temp;
}
else {
temp = copyArr[i];
copyArr[i] = copyArr[n - 1];
copyArr[n - 1] = temp;
}
}
}

buildPerms(len, chars);

// console.log(p);
var f = p.filter(function (elem) {
for (let i = 0; i < elem.length; i++) { // looping through characters of string
if (elem[i] === elem[i - 1]) { // if the letter before is same as current letter
return false; // value won't be in new array because of filtering
}
}
return true; // value will be in new array
});

return f.length;
}

console.log(permAlone("aab"));
console.log(permAlone("abcdefa"));
``````

Hope this is helpful for you.