March 2014 update
This commit is contained in:
parent
09687c4926
commit
a25938f123
1846 changed files with 21876 additions and 5203 deletions
|
|
@ -1,13 +1,15 @@
|
|||
use 5.10.0; # for given ... when construct
|
||||
sub balanced {
|
||||
my $depth = 0;
|
||||
for (split //, shift) {
|
||||
when('[') { ++$depth }
|
||||
when(']') { return if --$depth < 0 }
|
||||
}
|
||||
return !$depth
|
||||
sub generate {
|
||||
my $n = shift;
|
||||
my $str = '[' x $n;
|
||||
substr($str, rand($n + $_), 0) = ']' for 1..$n;
|
||||
return $str;
|
||||
}
|
||||
|
||||
for (']', '[', '[[]', '][]', '[[]]', '[[]]]][][]]', 'x[ y [ [] z ]][ 1 ][]abcd') {
|
||||
print balanced($_) ? "" : "not ", "balanced:\t'$_'\n";
|
||||
sub balanced {
|
||||
shift =~ /^ (\[ (?1)* \])* $/x;
|
||||
}
|
||||
|
||||
for (0..8) {
|
||||
my $input = generate($_);
|
||||
print balanced($input) ? " ok:" : "bad:", " '$input'\n";
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,3 @@
|
|||
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";
|
||||
shift =~ /^ ( [^\[\]]++ | \[ (?1)* \] )* $/x;
|
||||
}
|
||||
|
|
|
|||
8
Task/Balanced-brackets/Perl/balanced-brackets-3.pl
Normal file
8
Task/Balanced-brackets/Perl/balanced-brackets-3.pl
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
sub balanced {
|
||||
my $depth = 0;
|
||||
for (split //, shift) {
|
||||
if ($_ eq '[') { ++$depth }
|
||||
elsif ($_ eq ']') { return if --$depth < 0 }
|
||||
}
|
||||
return !$depth
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue