Balanced brackets: Difference between revisions
Content added Content deleted
m (→{{header|REXX}}: moved '''output''' outside the <pre> section, changed an expression to a literal. -- ~~~~) |
m (→{{header|REXX}}: re-structured DO loops and main subroutine. -- ~~~~) |
||
Line 2,396: | Line 2,396: | ||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
<lang rexx>/*REXX program |
<lang rexx>/*REXX program to check for balanced brackets [] */ |
||
@.=0 |
@.=0 |
||
yesno.0=left('',40) 'unbalanced' |
yesno.0 = left('',40) 'unbalanced' |
||
yesno.1='balanced' |
yesno.1 = 'balanced' |
||
q='[][][][[]]' ; call checkBal q; say yesno.result q |
q='[][][][[]]' ; call checkBal q; say yesno.result q |
||
Line 2,415: | Line 2,415: | ||
q=']]][[[[]' ; call checkBal q; say yesno.result q |
q=']]][[[[]' ; call checkBal q; say yesno.result q |
||
do j=1 for 40 |
do j=1 for 40 |
||
q=translate(rand(random(1,8)),'[]',01) |
q=translate(rand(random(1,8)),'[]',01) |
||
call checkBal q; if result=-1 then iterate |
call checkBal q; if result=='-1' then iterate |
||
say yesno.result q |
say yesno.result q |
||
end |
end |
||
exit |
exit |
||
/*───────────────────────────────────PAND subroutine────────────────────*/ |
|||
/*-------------------------------------subroutines----------------------*/ |
|||
pand: p=random(0,1); return p||\p |
pand: p=random(0,1); return p || \p |
||
/*───────────────────────────────────RAND subroutine────────────────────*/ |
|||
rand: pp=pand(); pp=pand()pp; pp=copies(pp,arg(1)) |
|||
rand: pp=pand(); pp=pand()pp; pp=copies(pp,arg(1)) |
|||
i=random(2,length(pp)); pp=left(pp,i-1)substr(pp,i) |
|||
return pp |
|||
/*─────────────────────────────────────check for balanced brackets [] */ |
|||
/*───────────────────────────────────CHECKBAL subroutine────────────────*/ |
|||
checkBal: procedure expose @.; |
checkBal: procedure expose @.; arg y /*check for balanced brackets [] */ |
||
if @.y then return '-1' |
nest=0; if @.y then return '-1' /*already done this expression ? */ |
||
@.y=1 /*indicate expression processed. */ |
@.y=1 /*indicate expression processed. */ |
||
do j=1 for length(y) |
do j=1 for length(y); _=substr(y,j,1) /*pick off character.*/ |
||
_=substr(y,j,1) |
|||
if _=='[' then nest=nest+1 |
if _=='[' then nest=nest+1 |
||
else do; nest=nest-1; if nest<0 then return 0; end |
else do; nest=nest-1; if nest<0 then return 0; end |