Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Divide a list of string into substrings

by jcb (Vicar)
on Jun 22, 2020 at 04:35 UTC ( #11118335=note: print w/replies, xml ) Need Help??


in reply to Divide a list of string into substrings

This was a fun exercise and here is a script that produces the expected results (in sorted order) and should be considerably faster than a full brute force search:

#!/usr/bin/perl # -*- CPerl -*- use strict; use warnings; # Goals: # * Find a set of shared substrings for a set of input strings such th +at: # ** Each substring is at least 3 characters long. # ** Minimize total substring length, counting each substring as extra + 2. use constant MIN_SUBSTRING_LEN => 3; use constant PER_SUBSTRING_OVERHEAD => 2; # sample input: my @list=("set abcde-efghi 12345", "set abcde-ijkl 12345", "clr abcde-efghi+123", "clr abcde-ijkl 12345"); # sample output: my @expected_substrings=("set","clr"," abcde-","efghi", "ijkl"," 12345","+123"); # cost of a solution set sub cost (@) { my $cost = PER_SUBSTRING_OVERHEAD * scalar @_; $cost += length shift while @_; return $cost } # algorithm: # attempt to split common prefixes and suffixes into separate substri +ngs; # terminate when this is no longer possible my @substrings = @list; my $made_progress = 1; my $last_output = ''; # find common prefixes # returns [ <prefix>, <tail>... ]... sub partition (@) { my @strings = sort @_; my @bins = (); my $prefix = $strings[0]; for (my $i = 0; $i < @strings; $i++) { next if $prefix eq substr($strings[$i], 0, length $prefix); my $new_prefix = $prefix; $new_prefix = substr $new_prefix, 0, -1 while length $new_prefix and $new_prefix ne substr($strings[$i], 0, length $new_prefix); if (length $new_prefix < MIN_SUBSTRING_LEN and @strings) { push @bins, [$prefix, map {substr $_, length $prefix} splice @strings, 0, $i]; $i = 0; $prefix = $strings[0]; } else { $prefix = $new_prefix; } } push @bins, [$prefix, map {substr $_, length $prefix} splice @string +s] if @strings; return @bins } while ($made_progress) { # find prefixes my %new_substrings = (); my @bins = partition @substrings; $new_substrings{$_}++ for map {@$_} @bins; @substrings = sort keys %new_substrings; # repeat for suffixes %new_substrings = (); @bins = partition map scalar reverse, @substrings; $new_substrings{$_}++ for map {@$_} @bins; @substrings = grep length, sort map scalar reverse, keys %new_substr +ings; $made_progress = ($last_output ne join(':', @substrings)); $last_output = join(':', @substrings); } print "results: (cost ",cost(@substrings),")\n"; print $_, "\n" for @substrings;

This script does not really try to produce a minimal-cost result set at all — it simply produces a solution quickly by repeatedly "peeling off" common prefixes and suffixes. The same sub partition is used for both, by simply reversing the strings to make suffixes into prefixes. It works by finding a common prefix, reducing that prefix while traversing the sorted input, and ending a group when the prefix is below the threshold length.

(thanks to LanX for the reminder to use a hash for unique keys)

Replies are listed 'Best First'.
Re^2: Divide a list of string into substrings
by Anonymous Monk on Jun 22, 2020 at 08:13 UTC

    Thanks for your script.

    The approch is good to find a fast solution. If the common substring is in the middle of each string this solution will not find it.

      If the common substring is in the middle of each string this solution will not find it.

      That is the major limitation to this approach. On the other hand, your sample data did not include those and this approach could be a useful preprocessing step to greatly the reduce the volume of input before applying a much-less-efficient brute force search to find those inner common substrings, if they are even a problem.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (5)
As of 2020-11-27 03:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?