in reply to Finding all substrings
Using Benchmark.pm and a test case against random words from /usr/dict/words I found this to be 300% faster over 100,000 iterations. Not bad, but I bet we could do better!{ my @cache; # a cache of substring-finding subs sub substrings { my $string = shift; my $length = length $string; # use cached sub if we have one return $cache[$length]->($string) if exists $cache[$length]; # create sub to find substrings for this length my $sub = 'sub { $_ = shift; return ('; foreach my $length (1..length($string)) { foreach my $offset (0..length($string)-$length) { $sub .= "substr(\$_,$offset,$length),"; } } $sub .= ")};"; $cache[$length] = eval $sub; # and use it return $cache[$length]->($string); } }
-sam
PS: Has anyone noticed that <code> doesn't deal with hard tabs right? Copy-and-paste from Emacs is unpleasant.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Finding all substrings
by samtregar (Abbot) on Apr 24, 2002 at 19:13 UTC | |
|
Re: Finding all substrings
by Dominus (Parson) on Apr 24, 2002 at 19:34 UTC | |
by samtregar (Abbot) on Apr 24, 2002 at 19:39 UTC | |
by Russ (Deacon) on Apr 24, 2002 at 19:49 UTC | |
by MeowChow (Vicar) on Apr 25, 2002 at 00:20 UTC | |
by BUU (Prior) on Apr 25, 2002 at 02:02 UTC |