R56 has asked for the wisdom of the Perl Monks concerning the following question:
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!
|
|---|