Hey guys!

I have to make a script for the longest common substring. Since it's a 'known' problem, I searched around for a bit and stumbled across the algorithm:

my $str1 = 'stringone'; my $str2 = 'stringtwo'; my $l_length = 0; my $len1 = length $str1; my $len2 = length $str2; my @char1 = (undef, split(//, $str1)); my @char2 = (undef, split(//, $str2)); my @lc_suffix; my @substrings; for my $n1 ( 1 .. $len1 ) { for my $n2 ( 1 .. $len2 ) { if ($char1[$n1] eq $char2[$n2]) { $lc_suffix[$n1-1][$n2-1] ||= 0; $lc_suffix[$n1][$n2] = $lc_suffix[$n1-1][$n2-1] + 1; if ($lc_suffix[$n1][$n2] > $l_length) { $l_length = $lc_suffix[$n1][$n2]; @substrings = (); } if ($lc_suffix[$n1][$n2] == $l_length) { push @substrings, substr($str1, ($n1-$l_length), $l_length); } } } }

Works like a charm for a simple comparison between two predetermined strings, but my implementation requires a few tweaks:

Instead of only two predetermined strings, it has to read and compare from a previously input-fed array.

Use two limits that are already on the input. The first line of the input contains two numbers. First one tells us how many strings we should consider, second one tells us the minimum number of original strings where the substring should appear. The rest of the lines are the strings for comparison.

I'm handling the beginning like so:

open (IN, 'text.txt'); while (<IN>){ if ($_ =~ /^(\d)\s(\d)/){ $size = $1; $minmatch = $2; } else{ push(@array, $_); } }

So how could I make the other changes?

Thanks for helping!


In reply to longest common substring (with needed tweaks) by R56

Title:
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, details, 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, summary, 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.