Balanced brackets: Difference between revisions

added PL/I
(added PL/I)
Line 2,711:
[]][][[[][[]]][]][not OK
[[[][]]]]][][[]]][[[not OK</pre>
 
=={{header|PL/I}}==
<lang pli>*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;</lang>
Output:
<pre> balanced ''
balanced '[][][][[]]'
unbalanced '[][][][[]]]['
unbalanced '['
unbalanced ']'
balanced '[]'
unbalanced ']['
unbalanced '][]['
balanced '[[]]'
balanced '[[[[[[[]]]]]]]'
unbalanced '[[[[[]]]][]'
balanced '[][]'
unbalanced '[]][[]'
unbalanced ']]][[[[]'
balanced '[[a]][b]'
 
unbalanced '][[][[[[[]'
balanced '[[]][[[]]]'
unbalanced ']][[[[][[['
unbalanced '[[[][][[]]'
unbalanced ']]][[[[[]]'
balanced '[[[][][]]]'
unbalanced '[][][][[]['
unbalanced '[[]]]][[]['
unbalanced '[]][]]][[]'
unbalanced '][[][[[[[]'</pre>
 
=={{header|Prolog}}==
2,300

edits