Build a Permutation Generator - Build a Permutation Generator

Tell us what’s happening:

I “think” I have some kind of recursion happening, but for the life of me, I can’t figure out how to use the prefix and array variables to accumulate and record the permutations. It makes me think I don’t really understand recursion at all. Maybe I just can’t understand instructions.

Your code so far

function permuteString(str, pre, arr = []) {
  for (const char of str) {
    if (str.length === 0) {
      arr.push(pre);
      return arr;
    } 
    let i = str.indexOf(char);
    let pre = '';
    pre += str.slice(0, i) + str.slice(i + 1);
    console.log(`char=${char},s2=,pre=${pre},arr=${arr}`);
    permuteString(pre);
  }
}

permuteString("walk")

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36

Challenge Information:

Build a Permutation Generator - Build a Permutation Generator

Think about step 4 without thinking about the code to implement it. What is it asking you to do? Do you understand how the algorithm it describes will give you all of the permutations you want? THEN think about the code. Your code has a number of issues but I think if you “grokked” the algorithm better you’d spot most of them yourself.

(If it would help, you could describe your understanding of the algorithm here and we could help point you in the right direction.)