# From http://rosettacode.org/wiki/Longest_common_subsequence#Perl_6 # Be advised: I was not the original author of this code; I adapted and # refactored it to match the way I would have written it, but it may count # as plagiarism to you. sub lcs ( Str $xstr, Str $ystr ) { my @xs = $xstr.comb; my @ys = $ystr.comb; my @lengths = map { [ 0 xx (1+@ys) ] }, ^(1+@xs); for @xs.keys X @ys.keys -> $i, $j { @lengths[$i+1][$j+1] = @xs[$i] eq @ys[$j] ?? @lengths[$i][$j]+1 !! ( @lengths[$i][$j+1], @lengths[$i+1][$j] ).max; } my ( $x, $y ) = ( +@xs, +@ys ); my @r = gather while $x and $y { my $len_xy = @lengths[$x][$y]; if $len_xy == @lengths[$x-1][$y ] { $x-- } elsif $len_xy == @lengths[$x ][$y-1] { $y-- } else { take @xs[$x-1]; $x--; $y--; } } return @r.reverse.join(''); } my ( $s1, $s2 ) = $*IN.lines; say lcs( $s1, $s2 );