Longest common subsequence: Difference between revisions

Content added Content deleted
m (Replaced use of chains.size() with chains.empty().)
Line 3,173: Line 3,173:
<syntaxhighlight lang="ruby">func lcs(xstr, ystr) is cached {
<syntaxhighlight lang="ruby">func lcs(xstr, ystr) is cached {


xstr.is_empty && return xstr;
xstr.is_empty && return xstr
ystr.is_empty && return ystr;
ystr.is_empty && return ystr


var(x, xs, y, ys) = (xstr.ft(0,0), xstr.ft(1),
var(x, xs, y, ys) = (xstr.first(1), xstr.slice(1),
ystr.ft(0,0), ystr.ft(1));
ystr.first(1), ystr.slice(1))


if (x == y) {
if (x == y) {
x + lcs(xs, ys)
x + lcs(xs, ys)
} else {
} else {
[lcs(xstr, ys), lcs(xs, ystr)].max_by { .len };
[lcs(xstr, ys), lcs(xs, ystr)].max_by { .len }
}
}
}
}


say lcs("thisisatest", "testing123testing");</syntaxhighlight>
say lcs("thisisatest", "testing123testing")</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>