I've tried to smoothen the differences between your non-recursive but using regexp solution and mine, which is recursive but doesn't use any RX.
After benchmarking, you're the clear winner:
Benchmark: timing 2000 iterations of Krambambuli, blazar...
Krambambuli: 4 wallclock secs ( 3.28 usr + 0.01 sys = 3.29 CPU) @ 6
+07.90/s (n=2000)
blazar: 1 wallclock secs ( 0.80 usr + 0.00 sys = 0.80 CPU) @ 25
+00.00/s (n=2000)
Congrats! :)
Here's the code I've used for the benchmarking.
use strict;
use warnings;
use Benchmark;
use Data::Dumper;
use constant MIN => 2;
my $str = 'aabcdabcabcecdecd';
my $min_length = 2;
my $min_count = 2;
timethese(2000, {
'blazar' => sub { count1( $str ) },
'Krambambuli' => sub { count2( $str ) },
});
{
my %count;
sub count1 {
my( $string) = @_;
my $length = length( $string );
if ($length < MIN) {
$count{$_} == 1 and delete $count{$_} for keys %count;
return \%count;
}
for my $l (MIN..$length) {
my $s = substr( $string, 0, $l );
$count{ $s } += 1;
}
count1( substr( $string, 1 ) );
}
}
sub count2 {
local $_=shift;
my $l=length;
my %count;
for my $off (0..$l-1) {
for my $len (MIN .. $l-$off) {
my $s=substr $_, $off, $len;
$count{ $s } ||= ()= /$s/g;
}
}
$count{$_} == 1 and delete $count{$_} for keys %count;
\%count;
}
Update: Actually, it's in fact the other way round, my code is faster - I've just named the benchmarked subs wrongly. Duh! Sorry.
-
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.
|