Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

Re: Matching bits of 2 strings

by Fletch (Chancellor)
on Jan 22, 2002 at 07:31 UTC ( #140581=note: print w/replies, xml ) Need Help??

in reply to Matching bits of 2 strings

I had this problem come up a while back (in fact I think it was my question that prompted the thread on fwp about it . . .). At any rate, this was something I had lying around from it that benchmarks three solutions. You can decide for yourself if the first is cheating or if you really, really care about speed. :)

Also, note that these are returning the length of the common string not the string itself.

#!/usr/bin/perl use Benchmark qw( cmpthese ); use Inline C => <<EOF; int comlen(char *p, char *q) { int i = 0; while( *p && (*p++ == *q++) ) i++; return i; } EOF sub comlen_or { length((($_[0]^$_[1])=~m/^(\0+)/)[0]); } sub comlen_tr { my( $t ); return ($t=$_[0]^$_[1])=~ y/\0/\0/; } $a = "abcdefghijk"; $b = "abcdefg"; cmpthese( shift || 2_000_000, { inline_c => sub { comlen( $a, $b ) }, comlen_or => sub { comlen_or( $a, $b ) }, comlen_tr => sub { comlen_tr( $a, $b ) }, }, ); exit 0;

Replies are listed 'Best First'.
Re: Re: Matching bits of 2 strings
by japhy (Canon) on Jan 22, 2002 at 22:34 UTC
    You've beaten me to the use of C. I remembered that it would be faster to call an XS (or Inline::C) function here. However, I'd like to point out that using tr/// for this problem is not a help at all. Using tr/\0// merely tells you how many characters are the same between the two words in total, not how many characters are the same at the start of the string. This is the fatal flaw. I believe this flaw existed in the LCS presentation at a YAPC in years gone by.

    Example: calling the function with "brought" and "wrought" should return 0, except that the tr/// solution returns 6.

    Jeff[japhy]Pinyan: Perl, regex, and perl hacker.
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://140581]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (2)
As of 2018-02-18 09:52 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (253 votes). Check out past polls.