No Repeats Please: help

No Repeats Please: help
0

#1

When I return norepeat it brings up the correct permutations but when i return norepeat.length i get 0. Any help would be appreciated.


function getAllPermutations(string) {
  var reg = /([a-z])(\1)/;
  var results = [];
  var norepeat = [];

  if (string.length === 1) {
    results.push(string);
    return results;
  }

  for (var i = 0; i < string.length; i++) {
    var firstChar = string[i];
    var charsLeft = string.substring(0, i) + string.substring(i + 1);
    var innerPermutations = getAllPermutations(charsLeft);
    for (var j = 0; j < innerPermutations.length; j++) {
      results.push(firstChar + innerPermutations[j]);
    }
  }
  
  for (var k=0; k<results.length; k++) {
    if (results[k].search(reg) < 0) {
      norepeat.push(results[k]);
    }
  }
  return norepeat.length;
}

getAllPermutations("aab");

#2

When I return norepeat, it gives me ["ab", "ba"] ["ab", "ba"] [] []. Is this the result you were expecting/had? If it is, taking the norepeat variable out of the function will let it correctly store those results. I’m assuming that having it set to [] everytime the function recurs means that the final result is [] (in your given test case, anyway.)

Shouldn’t your test case evaulate to aba aba though?


#3

if you change return norepeat.length to … return norepeat;
if you do … let results = getAllPermutations(“aab”);

then if you do console.log(results.length) you get a number .
when i went in to debug just the line … return norepeat.length … its not doing what you expect it to do … in fact it returns the length 5 times … twice with value of 2 then with value of 0 … would suspect this is to do with the way you have your recursion set up … so i would say your code works but the little quirk at the end is unexpected … and not sure how to sort it