How to resolve the algorithm Balanced brackets step by step in the PL/I programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Balanced brackets step by step in the PL/I programming language

Table of Contents

Problem Statement

Task:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Balanced brackets step by step in the PL/I programming language

Source code in the pl/i programming language

*process m or(!) s attributes source;
 cb: Proc Options(main);
 /* PL/I program to check for balanced brackets [] ********************
 * 07.12.2013 Walter Pachl translated from REXX Version 2
 *********************************************************************/
 Dcl v Char(20) Var;
 Dcl (i,j) Bin Fixed(31);
 Dcl r Bin Float(53);

 Call testbal('');                  /* first some user written tests */
 Call testbal('[][][][[]]');
 Call testbal('[][][][[]]][');
 Call testbal('[');
 Call testbal(']');
 Call testbal('[]');
 Call testbal('][');
 Call testbal('][][');
 Call testbal('[[]]');
 Call testbal('[[[[[[[]]]]]]]');
 Call testbal('[[[[[]]]][]');
 Call testbal('[][]');
 Call testbal('[]][[]');
 Call testbal(']]][[[[]');
 Call testbal('[[a]][b]');
 Put Edit(' ')(Skip,a);
 r=random(12345);                      /* then some generated ones   */
 Do i=1 To 10;
   v='';
   Do j=1 To 10;
     r=random();
     If r>0.5 Then v=v!!']';
              Else v=v!!'[';
     End;
   Call testbal(v);
   End;
 Return;

 testbal: Proc(s);          /* test the given string and show result */
 Dcl s Char(*);
 Dcl yesno(0:1) Char(20) Var Init('unbalanced','  balanced');
 Put Edit(yesno(checkbal(s)),''''!!s!!'''')(Skip,a,x(1),a);
 End;

 checkBal: proc(s) Returns(Bin Fixed(31));
                                    /*check for balanced brackets [] */
 Dcl s Char(*);
 Dcl nest Bin Fixed(31) Init(0);
 Dcl i Bin Fixed(31);
 Do i=1 To length(s);
   Select(substr(s,i,1));
     When('[') nest+=1;
     When(']') Do;
       If nest=0 Then return(0);
       nest-=1;
       End;
     Otherwise;
     End;
   End;
 Return(nest=0);
 End;

 End;

  

You may also check:How to resolve the algorithm Special variables step by step in the PL/I programming language
You may also check:How to resolve the algorithm Flatten a list step by step in the PL/I programming language
You may also check:How to resolve the algorithm Averages/Mean time of day step by step in the PL/I programming language
You may also check:How to resolve the algorithm Parse an IP Address step by step in the PL/I programming language
You may also check:How to resolve the algorithm Monty Hall problem step by step in the PL/I programming language