Build a Permutation Generator - Build a Permutation Generator

Tell us what’s happening:

my test is logging the correct result, but I feel like for some reason when I call the method it does’nt return the correct array, what am I missing here?

Your code so far

function permuteString(string, prefix = '', array = []){
  if(string.length === 0) {
    array.push(prefix);
    
    if(array.length == getPermuteAmount(prefix.length))
    {
      console.log([...new Set(array)]);
      return [...new Set(array)];
    }
  }
  
  for(const char in string){
    let s = string.split("");
    s.splice(char, 1);
    s = s.join("");
    permuteString(s, prefix + string[char], array);
  }
}

function getPermuteAmount(length){
  let amm = 0;
  let len = length;
  while(len > 0){
    amm += len;
    len--;
  }
  return amm;
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 Edg/134.0.0.0

Challenge Information:

Build a Permutation Generator - Build a Permutation Generator

I don’t think you can return in the middle of the recursion like this, you need to move the return to the end of your function…

I don’t really understand it right now but I think the console.log works because it logs it after unwinding the call stack…

but you can’t return where the console.log is or it returns too early, without finishing all of the recursive calls that have stacked up.

This isn’t a good explanation, but do you see what I’m thinking?

1 Like

not sure if that is what you ment but just tried movind the returning condition to after the recursive call like this:

function permuteString(string, prefix = '', array = []){
  
  for(const char in string){
    let s = string.split("");
    s.splice(char, 1);
    s = s.join("");
    permuteString(s, prefix + string[char], array);
  }
  
  if(string.length === 0) {
    array.push(prefix);
    
    if(array.length == getPermuteAmount(prefix.length))
    {
      console.log([...new Set(array)]);
      return [...new Set(array)];
    }
  }
}

and it still didn’t work, is this what you ment?

I tried moving it to the very end of the function, the last point before the last bracket.

I hope someone could have a better explanation though.

1 Like

don’t really understood how it works but got it to work, will try to figure out why :sweat_smile: thanks for the help.

Me neither… I was following some kind of intuition.

@lasjorg @JeremyLT @ILM Found the solution to this but I’m not really able to explain why it works. Any insight here?

no, the solution I wrote was apparently right but never passed tests