Recursively print all permutations of a string (Javascript)

singmotor picture singmotor · Oct 8, 2016 · Viewed 41.4k times · Source

I've seen versions of this question for other languages, but not for JS.

Is it possible to do this recursively in one function?

I understand that I need to take the first element in the string, and then append it to each solution to the recursion on the remainder of the string. So logically, I understand how the recursion needs to go. I just don't understand how to append the first char onto each of the recursive solutions

var myString = "xyz";

function printPermut(inputString){
    var outputString;
    if(inputString.length === 0){
        return inputString;
    }
    if(inputString.length === 1){
        return inputString;
    }
    else{
       for(int i = 0; i<inputString.length(); i++){
           //something here like: 
           //outputString = outputString.concat(printPermut(inputString.slice(1))??
           //maybe store each unique permutation to an array or something?
       } 
    }
}

Answer

Syntac picture Syntac · Oct 8, 2016

Let's write a function that returns all permutations of a string as an array. As you don't want any global variables, returning the permutations is crucial.

  function permut(string) {
  if (string.length < 2) return string; // This is our break condition

  var permutations = []; // This array will hold our permutations
  for (var i = 0; i < string.length; i++) {
    var char = string[i];

    // Cause we don't want any duplicates:
    if (string.indexOf(char) != i) // if char was used already
      continue; // skip it this time

    var remainingString = string.slice(0, i) + string.slice(i + 1, string.length); //Note: you can concat Strings via '+' in JS

    for (var subPermutation of permut(remainingString))
      permutations.push(char + subPermutation)
  }
  return permutations;
}

To print them, just iterate over the array afterwards:

 var myString = "xyz";
 permutations = permut(myString);
 for (permutation of permutations)
   print(permutation) //Use the output method of your choice

Hope I could help you with your question.