Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Matching bits of 2 strings

by Fletch (Bishop)
on Jan 22, 2002 at 07:31 UTC ( [id://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?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://140581]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (5)
As of 2024-04-25 16:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found