Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: An efficient way to gather a common portion of several strings' beginnings

by atcroft (Abbot)
on Nov 15, 2015 at 08:22 UTC ( [id://1147719]=note: print w/replies, xml ) Need Help??


in reply to An efficient way to gather a common portion of several strings' beginnings

I would suggest starting by ordering your array by string length, shortest to longest. Then, take element 0 as your first approximation at the shortest substring and compare it to the same length section (via substr()) to the next string. If they do not match, reduce the test sequence until you arrive at a match, or an empty string. Repeat until you have examined all strings, or have an empty approximation string.

Untested code example:

my @string = sort { length $a <=> length $b } ( qw/ quux asdfasdfasdf asdfasdf asdfzxcv as / ); my $common = shift @string; while ( my $teststr = shift @string and length $common ) { if ( $common eq substr( $teststr, 0, length $common ) ) { next; } my $flag = length $common; while ( $flag ) { if ( $common eq substr( $teststr, 0, $flag ) ) { $flag = 0; } else { $flag--; $common = substr( $common, 0, $flag ); } } } # print $common;

Hope that helps.

Update: 2015-11-15
Fixed errors in code sample. (My thanks to oiskuu for pointing their existence!)

  • Comment on Re: An efficient way to gather a common portion of several strings' beginnings
  • Download Code

Log In?
Username:
Password:

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

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

    No recent polls found