Longest common subsequence: Difference between revisions

m
→‎Bit Vector: fiddle with sigils and layout
(→‎{{header|Picat}}: Split into subsections. Added {{out}})
m (→‎Bit Vector: fiddle with sigils and layout)
Line 2,667:
Bit parallel dynamic programming with nearly linear complexity O(n). It is fast.
<lang perl6>sub lcs(Str $xstr, Str $ystr) {
my ($@a,$ @b) := ([$xstr.comb],[ $ystr.comb]);
my (%positions, @Vs, $lcs);
 
myfor @a.kv -> $i, $x { %positions;{$x} +|= 1 +< ($i % @a) }
for $a.kv -> $i,$x { $positions{$x} +|= 1 +< $i };
 
my $S = +^ 0;
myfor $Vs(0 =..^ @b) -> $j [];{
my ($y,$u = $S +& (%positions{@b[$j]} // 0);
for @Vs[$j] = $S = (0..$S + $b-1u) ->+| ($jS {- $u)
$y = $positions{$b[$j]} // 0;
$u = $S +& $y;
$S = ($S + $u) +| ($S - $u);
$Vs[$j] = $S;
}
 
my ($i, $j) = (+$@a-1, +$@b-1);
while ($i ≥ 0 and $j ≥ 0) {
my $result = "";
while ($i >= 0 &&unless (@Vs[$j] >=+& 0(1 +< $i)) {
if ( $lcs [R~]= @a[$i] unless $j and ^@Vs[$j-1] +& (1 +< $i)) { $i-- };
else { $j--
unless ($j && +^$Vs[$j-1] +& (1 +< $i)) {
$result = $a[$i] ~ $result;
$i--;
}
$j--;
}
$u = $S +& $y;i--
}
return $result;lcs
}
 
2,392

edits