Advertisement
asweigart

Balnaced Parens JS

Jun 11th, 2021
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. <script type="text/javascript">
  2. function getBalancedParens(pairs, openRem, closeRem, current, indent) {
  3. if (openRem === undefined) {
  4. openRem = pairs;
  5. }
  6. if (closeRem === undefined) {
  7. closeRem = pairs;
  8. }
  9. if (current === undefined) {
  10. current = "";
  11. }
  12. if (indent === undefined) {
  13. indent = 0;
  14. }
  15.  
  16. document.write(".".repeat(indent) + "Start of pairs=" + pairs + ", openRem=" + openRem + ", closeRem=" + closeRem + ", current=\"" + current + "\"<br />");
  17. if (openRem === 0 && closeRem === 0) {
  18. // BASE CASE
  19. document.write(".".repeat(indent) + "1st base case. Returning " + [current] + "<br />");
  20. return [current];
  21. }
  22.  
  23. // RECURSIVE CASE
  24. let results = [];
  25. if (openRem > 0) {
  26. document.write(".".repeat(indent) + "Adding open parenthesis.<br />");
  27. Array.prototype.push.apply(results, getBalancedParens(pairs, openRem - 1, closeRem, current + '(', indent + 1));
  28. }
  29. if (closeRem > openRem) {
  30. document.write(".".repeat(indent) + "Adding close parenthesis.<br />");
  31. Array.prototype.push.apply(results, getBalancedParens(pairs, openRem, closeRem - 1, current + ')', indent + 1));
  32. }
  33.  
  34. // BASE CASE
  35. document.write(".".repeat(indent) + "2nd base case. Returning " + results + "<br />");
  36. return results;
  37. }
  38.  
  39. document.write("All combinations of 3 balanced parentheses:<br />");
  40. document.write("Results: ", getBalancedParens(3));
  41. </script>
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement