How to print all permutations of a string in JavaScript

1 Answer

0 votes
function swap(s, i, j) {
    let temp;
    let charArray = s.split("");
     
	temp = charArray[i];
	charArray[i] = charArray[j];
	charArray[j] = temp;
     
  return (charArray).join("");
}
  
  
function print_permutations(str, left, right) {
    if (left == right)
      console.log(str);
  else {
      for (let i = left; i <= right; i++) {
           str = swap(str, left, i);
           print_permutations(str, left + 1, right);
           str = swap(str, left, i);
       }
  }
}
  
 
let str = "abcd";
 
print_permutations(str, 0, str.length - 1);
   
   
     
     
     
/*
run:
     
"abcd"
"abdc"
"acbd"
"acdb"
"adcb"
"adbc"
"bacd"
"badc"
"bcad"
"bcda"
"bdca"
"bdac"
"cbad"
"cbda"
"cabd"
"cadb"
"cdab"
"cdba"
"dbca"
"dbac"
"dcba"
"dcab"
"dacb"
"dabc"
     
*/

 



answered Sep 30, 2021 by avibootz
edited Oct 29, 2021 by avibootz
...