Thanks. I forgot to include the
memoize('lcs');
that's why my code took so long to run. I also found this brute force method in Perl Monk and ran a comparison on both method and found that the brute force method actually ran faster. This does not make sense at all.
LCSS method:
# lcs.pl
use strict;
use Memoize;
sub longerOf {
my ($x, $y) = @_;
return (length $x > length $y) ? $x : $y;
}
memoize('lcs');
sub lcs {
my ($a, $b) = @_;
if ($a eq "" || $b eq ""){
return "";
}
my ($az, $bz) = (chop $a, chop $b);
if ($az eq $bz){
return lcs($a, $b) . $az;
} else {
return longerOf(
lcs($a . $az, $b),
lcs($b . $bz, $a));
}
}
while (1){
print "1: "; my $a = <>; chomp $a;
print "2: "; my $b = <>; chomp $b;
$start = time();
print "LCS: ", lcs($a, $b), "\n\n";
$end = time();
print "<br>Time taken was ", ($end - $start), " seconds";
$start = time();
print "Brute Force: ", lcsbruteforce($a, $b), "\n\n";
$end = time();
print "<br>Time taken was ", ($end - $start), " seconds";
}
sub lcsbruteforce {
my($x, $y) = @_;
my(@v, $cx, $cy, $left, $above);
for my $xi (0 .. length($x) - 1) {
$cx = substr $x, $xi, 1;
for my $yi (0 .. length($y) - 1) {
$cy = substr $y, $yi, 1;
if ($cx eq $cy) {
$v[$xi][$yi] = 1 + (($xi && $yi) ? $v[$xi - 1][$yi - 1] : 0);
} else {
$left = ($xi && $v[$xi - 1][$yi]) || 0;
$above = ($xi && $v[$xi][$yi - 1]) || 0;
$v[$xi][$yi] = ($left > $above) ? $left : $above;
}
}
}
return $v[length($x) - 1][length($y) - 1];
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.