in reply to fast bit twiddling

Assuming that the description a string of 0s and 1s of some length (lets say "1010101011") means string of bytes where each byte is either '0' or '1', and that the list of indices is subject to change with each call, then I'd try something like this.

sub buk2{ my $s = shift; substr $s, $_-1, 1 eq substr $s, $_, 1 and return for @_; return 1; }

It fails quickly if possible, and avoids creating lots of intermediate scalars or arrays.

If the '1's and '0's are bits encoded in a numeric value and the list of indices are reused, then zaxo's method is probably much quicker.


Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail

Replies are listed 'Best First'.
Re: Re: fast bit twiddling
by emazep (Priest) on May 04, 2004 at 21:13 UTC
    There's a mistake here, since the eq operator has an higher precedence than the comma.
    The sub should be written this way:
    sub buk2{ my $s = shift; substr($s, $_-1, 1) eq substr($s, $_, 1) and return for @_; return 1; }
    Oddly enough, after the correction above this solution proves to be the fastest (probably because it reaches the first return more frequently.)
    See here for the updated benchamark results.

    Cheers, Emanuele.

      Nice pickup.++


      Examine what is said, not who speaks.
      "Efficiency is intelligent laziness." -David Dunham
      "Think for yourself!" - Abigail
        Congratulations for the fastest solution ;-) ++