Advertisement
asweigart

Permutation JavaScript

Jun 6th, 2021
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. <script type="text/javascript">
  2. function getPerms(chars) {
  3. document.write('Calling getPerms("' + chars + '")<br />');
  4. if (chars.length === 1) {
  5. // BASE CASE
  6. document.write("Base case, returning " + chars + "<br />");
  7. return [chars];
  8. }
  9. // RECURSIVE CASE
  10. let permutations = [];
  11. let head = chars[0];
  12. let tail = chars.substring(1);
  13. let tailPermutations = getPerms(tail);
  14. tailPermutations.forEach(function(tailPerm) {
  15. document.write("For " + chars + " putting head " + head + " in all places in " + tailPerm + "<br />");
  16. for (let i = 0; i < tailPerm.length + 1; i++) {
  17. let newPerm = tailPerm.slice(0, i) + head + tailPerm.slice(i);
  18. document.write("New permutation: " + newPerm + "<br />");
  19. permutations.push(newPerm);
  20. }
  21. });
  22. document.write("All permutations of " + chars + " are " + permutations + "<br />");
  23. return permutations;
  24. }
  25.  
  26. document.write("Permutations of \"ABC\":<br />");
  27. document.write("Result: " + getPerms("ABC"));
  28. </script>
  29.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement