blib/lib/Number/Closest.pm

filter: Statementstmt 100% 25 / 25 Branchbran 75.0% 3 / 4 Conditioncond 50.0% 1 / 2 MC/DCmcdc 0.0% 0 / 1 Subroutinesub 100% 3 / 3 Podpod 0.0% 0 / 2 totaltotal 86.4% 32 / 37 CC 4 SCAR 11.0
CC
4
Cov
94%
find
4.0
BEGIN
1.0
analyze
1.0
CRAP 3.0
↑ Summary
1 package Number::Closest;
2  
3 2 our $VERSION = '0.06';
4  
5 2 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 2 has 'number' => (isa => 'Num', is => 'rw', required => 1);
8 2 has 'numbers' => (isa => 'ArrayRef[Num]', is => 'rw', required => 1);
9  
10 3 ▶sub analyze {
Subroutine analyze: called CC=1 SCAR=0.0
Pod undocumented
11 3 my($self)=@_;
12  
13 3 my @dist = sort { $a->[1] <=> $b->[1] } map { [$_, abs($_ - $self->number)] } sort {$a <=> $b} @{$self->numbers};
14  
15 \@dist
16 3 }
17  
18 2 ▶sub find {
Subroutine find: called CC=4 SCAR=13.9
Pod undocumented
19 2 my($self,$amount)=@_;
20  
21 2 ▶ $amount ||= 1;
Condition50%1/2
$amount ||= 1
l!l
20
MC/DC0%0/1
$amount ||= 1
$amount
Truth table50%1/2
A
A= $amount
Aresult
11
00
22  
23 2 my $list = $self->analyze;
24
25 2 ▶ my $n = $amount <= scalar @$list ? $amount : scalar @$list ;
Branch: 1 branch
BranchTrueFalseTotal
$amount <= scalar @$list ? : 2 0 2
26  
27 #warn "N: $n";
28  
29 2 my @closest = @{$list}[0..($n-1)] ;
30  
31 2 my @c = map { $_->[0] } @closest;
32
33 #use Data::Dumper;
34 #warn Dumper \@closest, \@c;
35  
36 2 ▶ if ($amount == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($amount == 1) { } 1 1 2
37 1 $c[0] ;
38 } else {
39 1 \@c;
40 }
41  
42 }
43  
44  
45  
46  
47 =head1 NAME
48  
49 Number::Closest - Find number(s) closest to a number in a list of numbers
50  
51 =head1 SYNOPSIS
52  
53 use Number::Closest;
54  
55 my $finder = Number::Closest->new(number => $num, numbers => \@num) ;
56 my $closest = $finder->find; # finds closest number
57 my $closest_two = $finder->find(2) ; # gives arrayref of two closest numbers in list
58
59 # or, all in one shot
60 Number::Closest->new(number => $num, numbers => \@num)->find(1) ;
61
62  
63  
64  
65 =head1 SEE ALSO
66  
67 L<http://stackoverflow.com/questions/445782/finding-closest-match-in-collection-of-numbers>
68  
69 =head1 AUTHOR
70  
71 Currently maintained by Mike Accardo, <accardo@cpan.org>
72  
73 Original author Terrence Monroe Brannon.
74  
75 =head1 COPYRIGHT
76  
77 Copyright (c) 2015 Mike Accardo
78 Copyright (c) 1999-2014 Terrence Brannon
79  
80 This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
81  
82 =cut
83  
84 2 1; # End of Number::Closest
↑ Summary