# more update: this is the tested version now!!
sub CountSubstrings { # $string1, $string2, $substr_length
my $l = pop @_;
my %found = ();
my %match = ();
my $first = 2;
my $string1 = $_[0];
for my $string ( @_ ) {
$first --;
my $ls = length( $string );
my $limit = $ls - $l + 1;
for ( my $i = 0; $i < $limit; $i++ ) {
my $sbstr = substr( $string, $i, $l );
$first or defined ( $match{$sbstr} ) && next();
$found{ $sbstr }{ $string } ||= 1;
$first and next;;
defined ( $found{ $sbstr }{ $string1 } )
and $match{ $sbstr } = 1;
}
}
Count( keys %match );
}
sub Count { 1+$#_ };
Description of alggorithm:
Store all substrings of string 1 of the given length in subhash $found{ $string1 };
do the same for string 2 but in addition lookup in the first hash and record any matches in the %match hash. The suggested opportunities for optimisation include (a) only need to check matches for the substring iteration of the second string. (b) only need to build the substring for string 2 if there is no match found in the match hash.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|