Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
My most revered monks,

The subroutine below compute the number of mismatches between two strings (they are always equal) - usually called Hamming Distance.

However my code below is painfully slow. I am terribly in need of a super fast way to do this. In particular it has to process millions of string pairs.

Thus I turn to you my brother monks, for illumination in this matter.
#!/usr/bin/perl -w use strict; my $s1 = 'AAAAA'; my $s2 = 'ATCAA'; my $s3 = 'AAAAA'; hd($s1,s2) # will give value 2 hd($s1,s3) # will give value 0 sub hd { #String length is assumed to be equal my ($k,$l) = @_; my $len = length ($k); my $num_mismatch = 0; for (my $i=0; $i<$len; $i++) { ++$num_mismatch if substr($k, $i, 1) ne substr($l, $i, 1); } return $num_mismatch; }
Update: Benchmark. Thanks so much everybody.
Rate Mine RJ BWK inman Mine 176987/s -- -65% -78% -80% RJ 504123/s 185% -- -38% -44% BWK 817943/s 362% 62% -- -9% inman 901871/s 410% 79% 10% -- *Note: Mine has already included the modification suggested by 'wazoox'.

Regards,
Edward

In reply to Hamming Distance Between 2 Strings - Fast(est) Way? by monkfan

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (4)
As of 2024-04-18 05:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found