Balanced brackets: Difference between revisions

Content added Content deleted
(→‎{{header|Perl}}: fixed brain damage)
Line 1,214: Line 1,214:
Straightforward depth counting:
Straightforward depth counting:
<lang Perl>use 5.10.0; # for given ... when construct
<lang Perl>use 5.10.0; # for given ... when construct
sub balanced2 {

sub balanced {
my $depth = 0;
my $depth = 0;
my @a = split('', shift);
my @a = split('', shift);
for (0 .. $#a) {
for my $i (0 .. $#a) {
given($a[$_]) {
given($a[$i]) {
when('[') { ++$depth }
when('[') { ++$depth }
when(']') { return if --$depth < 0 }
when(']') { return if --$depth < 0 }
}
}
Line 1,227: Line 1,226:
}
}


for (']', '[', '[[]', '[]]', '[[]]', '[[]][][]]', 'x[ y [ [] z ]][ 1 ][]abcd') {
for (']', '[', '[[]', '][]', '[[]]', '[[]]]][][]]', 'x[ y [ [] z ]][ 1 ][]abcd') {
print balanced($_) ? "not " : "", "balanced:\t'$_'\n";
print balanced($_) ? "" : "not ", "balanced:\t'$_'\n";
}</lang>
}</lang>


Line 1,235: Line 1,234:
sub balanced {
sub balanced {
my $_ = shift;
my $_ = shift;
s/(\[(?:[^\[\]]++|(?1))*\])//g;
s/(\[(?:[^\[\]]++|(?1))*\])//g;
/[\[\]]/;
! /[\[\]]/;
}
}


for (']', '[', '[[]', '[]]', '[[]]', '[[]][][]]', 'x[ y [ [] z ]][ 1 ][]abcd') {
for (']', '[', '[[]', '][]', '[[]]', '[[]]]][][]]', 'x[ y [ [] z ]][ 1 ][]abcd') a{
print balanced($_) ? "not " : "", "balanced:\t'$_'\n";
print balanced($_) ? "" : "not ", "balanced:\t'$_'\n";
}</lang>
}</lang>


Both methods prints
Both methods print
<pre>balanced: ']'
<pre>not balanced: ']'
balanced: '['
not balanced: '['
balanced: '[[]'
not balanced: '[[]'
balanced: '[]]'
not balanced: '][]'
not balanced: '[[]]'
balanced: '[[]]'
balanced: '[[]][][]]'
not balanced: '[[]]]][][]]'
not balanced: 'x[ y [ [] z ]][ 1 ][]abcd'
balanced: 'x[ y [ [] z ]][ 1 ][]abcd'
</pre>
</pre>
The counting method could easily give where the first unbalanced bracket occured, though.
The counting method could easily give where the first unbalanced bracket occured, though.