File Coverage

blib/lib/LCS/Similar.pm
Criterion Covered Total %
statement 38 38 100.0
branch 16 16 100.0
condition 7 8 100.0
subroutine 9 9 100.0
pod 4 4 100.0
total 74 75 100.0


line stmt bran cond sub pod time code
1             package LCS::Similar;
2              
3 2     2   17317 use 5.010001;
  2         7  
4 2     2   11 use strict;
  2         4  
  2         43  
5 2     2   24 use warnings;
  2         4  
  2         1063  
6             our $VERSION = '0.03';
7             #use utf8;
8             #use Data::Dumper;
9              
10             sub new {
11 12     12 1 1711 my $class = shift;
12             # uncoverable condition false
13 12 100 66     85 bless @_ ? @_ > 1 ? {@_} : {%{$_[0]}} : {}, ref $class || $class;
  4 100       30  
14             }
15              
16             sub LCS {
17 49     49 1 344954 my ($self, $X, $Y, $compare, $threshold) = @_;
18              
19 49   100 18274   246 $compare //= sub { $_[0] eq $_[1] };
  18274         59559  
20              
21 49         76 my $m = scalar @$X;
22 49         68 my $n = scalar @$Y;
23              
24 49         74 my $c = [];
25 49         63 my ($i,$j);
26 49         134 for ($i=0;$i<=$m;$i++) {
27 659         1299 for ($j=0;$j<=$n;$j++) {
28 20446         47028 $c->[$i][$j]=0;
29             }
30             }
31 49         113 for ($i=1;$i<=$m;$i++) {
32 610         1310 for ($j=1;$j<=$n;$j++) {
33 19221         42532 $c->[$i][$j] = $self->max3(
34             &$compare(
35             $X->[$i-1],
36             $Y->[$j-1],
37             $threshold
38             ) + $c->[$i-1][$j-1],
39             $c->[$i][$j-1],
40             $c->[$i-1][$j],
41             );
42             }
43             }
44 49         139 my $path = $self->_lcs($X,$Y,$c,$m,$n,[],$compare, $threshold);
45 49         649 return $path;
46             }
47              
48              
49 8 100   8 1 663 sub max { ($_[1] > $_[2]) ? $_[1] : $_[2]; }
50              
51             sub max3 {
52 19233 100   19233 1 736768 ($_[1] >= $_[2])
    100          
    100          
53             ? ($_[1] >= $_[3]
54             ? $_[1] : $_[3]
55             )
56             : ($_[2] >= $_[3]
57             ? $_[2] : $_[3]
58             );
59             }
60              
61             sub _lcs {
62 49     49   100 my ($self,$X,$Y,$c,$i,$j,$L,$compare, $threshold) = @_;
63              
64 49   100     280 while ($i > 0 && $j > 0) {
65 635 100       1356 if ( &$compare($X->[$i-1],$Y->[$j-1], $threshold) ) {
    100          
66 435         25751 unshift @{$L},[$i-1,$j-1];
  435         1258  
67 435         581 $i--;
68 435         1901 $j--;
69             }
70             elsif ($c->[$i][$j] == $c->[$i-1][$j]) {
71 154         8697 $i--;
72             }
73             else {
74 46         790 $j--;
75             }
76             }
77 49         107 return $L;
78             }
79              
80             1;
81              
82             __END__