Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively print all permutations of a string (Javascript)

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?        }      } } 
like image 269
singmotor Avatar asked Oct 08 '16 00:10

singmotor


People also ask

How do you generate all permutations of an array?

You take first element of an array (k=0) and exchange it with any element (i) of the array. Then you recursively apply permutation on array starting with second element. This way you get all permutations starting with i-th element.


1 Answers

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.

like image 175
Syntac Avatar answered Sep 30 '22 04:09

Syntac