Balanced brackets: Difference between revisions

(adding gap)
Line 1,210:
rnd(n)=Strchr(vectorsmall(n,i,if(random(2),91,93)))
forstep(n=0,10,2,s=rnd(n);print(s"\t"if(balanced(s),"true","false")))</lang>
 
=={{header|Perl}}==
Straightforward depth counting:
<lang Perl>use 5.10.0; # for given ... when construct
 
sub balanced {
my $depth = 0;
my @a = split('', shift);
for (0 .. $#a) {
given($a[$_]) {
when('[') { ++$depth }
when(']') { return if --$depth < 0 }
}
}
return !$depth
}
 
for (']', '[', '[[]', '[]]', '[[]]', '[[]][][]]', 'x[ y [ [] z ]][ 1 ][]abcd') {
print balanced($_) ? "not " : "", "balanced:\t'$_'\n";
}</lang>
 
or use regexp:
<lang Perl>use 5.10.0; # for '++' non-backtrack behavior
sub balanced {
my $_ = shift;
s/(\[(?:[^\[\]]++|(?1))*\])//g;
/[\[\]]/;
}
 
for (']', '[', '[[]', '[]]', '[[]]', '[[]][][]]', 'x[ y [ [] z ]][ 1 ][]abcd') {
print balanced($_) ? "not " : "", "balanced:\t'$_'\n";
}</lang>
 
Both methods prints
<pre>balanced: ']'
balanced: '['
balanced: '[[]'
balanced: '[]]'
not balanced: '[[]]'
balanced: '[[]][][]]'
not balanced: 'x[ y [ [] z ]][ 1 ][]abcd'
</pre>
The counting method could easily give where the first unbalanced bracket occured, though.
 
=={{header|Perl 6}}==
Anonymous user