in reply to Producing a list of offsets efficiently

Greetings all
not sure how efficient this is but I thought I would pay homage to TimToady.
#!/usr/bin/perl -w use strict; my $string = "aXbcXdefgXhijXklmnopqrXstuvwXyz"; my $target = "X"; my $count = 0; my @indices = map{$count++;/$target/? $count-1:();}split //,$string; print "@indices"; exit


-InjunJoel
"I do not feel obliged to believe that the same God who endowed us with sense, reason and intellect has intended us to forego their use." -Galileo

Replies are listed 'Best First'.
Re^2: Producing a list of offsets efficiently
by tlm (Prior) on May 28, 2005 at 22:00 UTC

    not sure how efficient this is...

    Not very much at all :) . It corresponds to wmap in the table below:

    Rate wmap count wgrep wregex windex wmap 5.42/s -- -12% -60% -97% -98% count 6.13/s 13% -- -54% -97% -98% wgrep 13.5/s 148% 120% -- -93% -96% wregex 198/s 3558% 3132% 1372% -- -37% windex 317/s 5741% 5062% 2251% 60% --

    the lowliest monk

      Of course wmap() and count() are going to be the slowest, because they go through the string twice: once to split it into individual elements, and again to compare each element to the desired one. The index() approach is very certainly the fastest. I wrote a function called aindex() a long time ago that did just that -- used index to step through a string and return all the indices of a substring in that string.

      Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
      How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart

        Yes, no surprises there on the ordering, though the hard numbers are eloquent; I would not have been able to predict a factor of ∼25 difference between wgrep and windex_1, say.

        the lowliest monk