Build a Permutation Generator - Build a Permutation Generator

Tell us what’s happening:

Hi all,

Would appreciate some help understanding where I am going wrong on this, I have got my head around what this problem is trying to achieve through recursion/backtracking and thought I was there however I am ending up with permutations longer than I would want. I’ve put various console logs in to track what is happening and it seems that as I am backtracking after adding the first result is added the prefix is keeping the value I have just submitted instead of resetting. many thanks

Your code so far

function permuteString(string, prefixValue = "", results=[]) {
  
  if (string.length ===  0){
    results.push(prefixValue)
    console.log(`adding [${prefixValue}] to results`)
    
    return results
  }
  
  
  for (let x of string ){
    console.log(`Pre - String ${string}, Prefix Value - ${prefixValue}`)
    let p = prefixValue += x
    console.log(`Locking ${p} from ${string}`)
    let list = string.split("") 
    list.splice(string.indexOf(x),1)
    list = list.join("")  
    console.log(`passing "${list}" to next function with ${p} as prefix\n`)
    permuteString(list, p, results)
    console.log(`Post - String ${string}, Prefix Value - ${prefixValue}`)
  }
  return results
}


console.log(permuteString("abc"))

Your browser information:

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

Challenge Information:

Build a Permutation Generator - Build a Permutation Generator

here do you want to change prefixValue?

1 Like

Try changing your addition assignment operator to just an addition operator.

1 Like

Thank you!! the difference 1 character makes…