*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;