# 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]; }
In reply to Re: Longest Common SubSequence Not Working Correctly
by Anonymous Monk
in thread Longest Common SubSequence Not Working Correctly
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |