Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??

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)

In reply to Re: Divide a list of string into substrings by jcb
in thread Divide a list of string into substrings by Anonymous Monk

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

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?

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

    How do I use this? | Other CB clients
    Other Users?
    Others drinking their drinks and smoking their pipes about the Monastery: (5)
    As of 2021-03-08 16:46 GMT
    Find Nodes?
      Voting Booth?
      My favorite kind of desktop background is:

      Results (126 votes). Check out past polls.