### Re^3: Longest Common SubSequence Not Working Correctly

 on Nov 14, 2007 at 05:16 UTC ( #650679=note: print w/replies, xml ) Need Help??

Thanks for the explanation. How would I modify the above brute force code to be truely brute force? Also, the code only print out the length of the sequence but does not print out the characters of the sequence. I tried putting in some print statement in between but it does not seem to work correctly. Any helps?
• Comment on Re^3: Longest Common SubSequence Not Working Correctly

Replies are listed 'Best First'.
Re^4: Longest Common SubSequence Not Working Correctly
by blokhead (Monsignor) on Nov 14, 2007 at 14:58 UTC
The lcsbruteforce algorithm maintains this big table of solutions to subproblems. In this example, it's maintaining just the length of the LCS. Just change it to maintain the actual substring itself:
```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);
\$v[\$xi][\$yi] = (\$xi && \$yi ? \$v[\$xi-1][\$yi-1] : "") . \$cx;
} else {
#        \$left = (\$xi && \$v[\$xi - 1][\$yi]) || 0;
#        \$above = (\$xi && \$v[\$xi][\$yi - 1]) || 0;
#        \$v[\$xi][\$yi] = (\$left > \$above) ? \$left : \$above;
\$left = (\$xi && \$v[\$xi - 1][\$yi]) || "";
\$above = (\$xi && \$v[\$xi][\$yi - 1]) || "";
\$v[\$xi][\$yi] = length(\$left) > length(\$above) ? \$left : \$above
+;

}
}
}
return \$v[length(\$x) - 1][length(\$y) - 1];
}
To change it to an actual brute force algorithm? That would be pretty strange. The brute force algorithm is:
```\$best = "";

for every subsequence \$s of \$x:
if \$s is also a subsequence of \$y:
\$best = \$s if length(\$s) > length(\$best);

return \$best;
Of course, the part where you get all subsequences and check for subsequence-ness is a pain. You can probably generate all subsequences using Algorithm::Loops, and perhaps use some regex stuff to check whether a string was a subsequence of another.

Create A New User
Node Status?
node history
Node Type: note [id://650679]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2017-08-17 08:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
Who is your favorite scientist and why?

Results (285 votes). Check out past polls.

Notices?