Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: Find repeated patterns in strings

by tlm (Prior)
on Aug 27, 2005 at 17:54 UTC ( [id://487171]=note: print w/replies, xml ) Need Help??


in reply to Find repeated patterns in strings

Actually, there's a much simpler solution (codewise):

sub findCycle { my $str = @_ ? shift : ''; $str =~ /^(.*?)\1*$/; return wantarray ? ( length $1, $1 ) : length $1; }
Though I suspect that, for long strings, a solution like the one you proposed but testing only cycles whose lengths are divisors of the input length would be faster. I'll do some benchmarking when I get a chance.

Update:

Caveat: take my benchmarks with a barrel of salt; despite many burns, I still manage to botch benchmarks routinely.

OK, one could test many possible variants. Below I test the case of a string of length about 10_000, consisting of a repeating pattern whose length is given as an input to the benchmarking script. I test three solutions: (0) the original algorithm (plus the minor optimization of not testing cycles longer than half the original string); (1) the modification of the original that tests only cycles whose lengths are divisors of the input string's slength; (2) the regex solution above. For a cycle length of 101 (in a string of length 9999), the results are:

Rate 0 1 2 0 906/s -- -58% -85% 1 2143/s 137% -- -64% 2 5966/s 559% 178% --
So, contrary to my expectation, the regex solution wins handily. On the other hand, for a cycle-free string of comparable length (9973), solution 1 is the clear winner:

Rate 0 2 1 0 17.0/s -- -89% -99% 2 155/s 812% -- -94% 1 2465/s 14431% 1494% --

And for short cycles in a long string, your original solution cleans house:

Rate 2 1 0 2 222/s -- -96% -98% 1 5023/s 2161% -- -52% 0 10479/s 4615% 109% --
That's for a cycle of length 3 in a string of length 9999.

Full code below:

use strict; use warnings; use Math::Pari 'divisors'; use Benchmark 'cmpthese'; my $len = shift || 3; srand 0; { $::input = join '', map int( rand 9 ), 1..$len; last if length $::input == findCycle_0( $::input ); redo; } $::input x= int( 10_000 / $len ); cmpthese( -1, { 0 => 'scalar findCycle_0( $::input )', 1 => 'scalar findCycle_1( $::input )', 2 => 'scalar findCycle_2( $::input )', } ); sub findCycle_0 { my $str = shift; my $copy = $str; my $strLen = length $str; for ( 1 .. $strLen/2 ) { $copy .= substr $copy, 0, 1, ''; return wantarray ? ($_, substr $str, 0, $_) : $_ if $str eq $copy; } return wantarray ? ($strLen, $str) : $strLen; } sub findCycle_1 { my $str = shift; my $strLen = length $str; for ( @{ divisors( $strLen ) } ) { my $copy = $str; $copy .= substr( $copy, 0, $_, '' ); return wantarray ? ($_, substr $str, 0, $_) : $_ if $str eq $copy; } } sub findCycle_2 { my $str = @_ ? shift : ''; $str =~ /^(.*?)\1*$/; return wantarray ? ( length $1, $1 ) : length $1; }

the lowliest monk

Replies are listed 'Best First'.
Re^2: Find repeated patterns in strings
by GrandFather (Saint) on Aug 27, 2005 at 20:58 UTC

    The divisors optimization occurred to me after I'd posted. I'd thought about the regex and, as you did, assumed it would be slow. Thank you for the work tlm!

    Lesson learned: it ain't obvious - benchmark!

    For the application domain this arose from findCycle_1 (divisors) is likely the best solution.


    Perl is Huffman encoded by design.
Re^2: Find repeated patterns in strings
by bioMan (Beadle) on Oct 04, 2005 at 17:16 UTC

    Gentlemen,

    We seem to have moved off point from the original problem. It was my original post (Search for identical strings) which sent Grandfather on his quest to optimize a search for identical substrings within a string.

    If I read this regex correctly it doesn't do what I originally asked for. That is, to find the longest set of identical substrings anywhere within a parent string.

    If I read the regex in findCycle_2 correctly it looks for a string of characters that must begin at the start of the parent string, and this substring is immediately followed by zero or more copies of itself to the end of the parent string. My original code also used a regex

    /(.+).*\1/

    The time estimate for a search of my original data set was around 3 years! (But my data set is very large.) The time estimate was based on how long it took to search a subset of my dataset. My biggest problem appears to be with regex backtracking.

    Anyway, back to findCycle_2. Using a test string of 'ABCDEFG123456ABCDEFG' findCycle_2 returns the entire 20 character string because it found the string but no copies of itself. If I force the presence of a second copy of the substring with

    /^(.*?)\1$/

    I get nothing. If I allow intervening trash with

    /^(.*?).*\1$/

    I get nothing. In order for the regex to find any occurrence of the longest paired substrings within a parent string it appears that the regex should be written

    /(.+).*\1/

    And this appears to return me to the three year run.

    I should note that Grandfather created a script which ran in under a minute for my entire dataset and found over 98% of the paired substrings.

    Mike

      You note that find_cycle_2seems to be broken, or at the very least doing something else.

      The lesson learned here is that benchmarks must be accompanied by tests to prove that the code actually works as intended.

      If it doesn't work, it doesn't matter how fast it is.

      -QM
      --
      Quantum Mechanics: The dreams stuff is made of

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://487171]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (4)
As of 2024-04-20 02:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found