Hi,
I tried to solve problem of nested parentheses. I have read in J.Friedl's book (Mastering Regular Expressions II ed.) about dynamic regexes - (??{code}).
The
problem is so:
You are given a sequence of (opening|closing) parentheses. What is the longest subsequence which is valid nested parentheses <for example: (), ()(), (()), ((())())>, and how much subsequences of that length occurs in the sequnce?
Here is the code how I am solving that problem:
@lines = <>;
$n=1000;
$long = '';
srand;
# generating one random sequence of length $n:
while ($n--){
$long .= qw<( )>[int (rand()*2) ]
}
$m;
$m = qr/\((?:|(??{$m})++)*\)/; # main thing
for (@lines, $long){
undef %occ;
map { ++$occ{(length)} } /$m+/g;
$max = 0;
$max < $_ and $max = $_ for keys %occ;
print $max," ",$occ{$max} || 1,$/;
}
# Example input:
)((())))(()())
))(
()(())()
((((()(((
(()())()(())()()())())()((()(()(())()()())((()(())()(()()()()))()(())(
+)(((()())()(()((())()(())(()))
# Example output:
6 2
0 1
8 1
2 1
28 1
662 1
You can test it in:
http://ideone.com/X8BUwy
Program works in different time, although $n is set to 1000. Sometimes it works 0.0 sec, sometimes >5 sec.
Any suggestions how to speed up regex? And how can someone determine when (with what sequences?) program will run slow?
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.