File Coverage

blib/lib/Algorithm/LSH/Hash/Hamming.pm
Criterion Covered Total %
statement 15 60 25.0
branch 0 14 0.0
condition 0 3 0.0
subroutine 5 10 50.0
pod 1 1 100.0
total 21 88 23.8


line stmt bran cond sub pod time code
1             package Algorithm::LSH::Hash::Hamming;
2 2     2   958 use strict;
  2         4  
  2         79  
3 2     2   11 use warnings;
  2         4  
  2         64  
4 2     2   10 use List::Util qw(max);
  2         3  
  2         247  
5 2     2   14 use Carp;
  2         2  
  2         183  
6 2     2   12 use base qw(Algorithm::LSH::Hash);
  2         4  
  2         1630  
7              
8             __PACKAGE__->mk_accessors($_) for qw( _indexes );
9              
10             our $SCALE = 100;
11              
12             sub do_hashing {
13 0     0 1   my $self = shift;
14 0           my $vector = shift;
15 0 0         if ( ref $vector ne 'ARRAY' ) {
16 0 0         carp("args should be an array_ref") and return;
17             }
18 0     0     my $d = $self->d || sub { $self->d( int @$vector ) }
19 0   0       ->();
20 0 0         if ( $d != scalar @$vector ) {
21 0 0         carp("invalid dimention number") and return;
22             }
23 0           my $L = $self->L;
24 0           my $unary_code = $self->_unarize($vector);
25 0           my @hashes;
26 0           for my $i ( 0 .. $L - 1 ) {
27 0           my @array;
28 0           for my $j ( @{ $self->_pickuped_indexes->[$i] } ) {
  0            
29 0           push( @array, $unary_code->[$j] );
30             }
31 0           push( @hashes, \@array );
32             }
33 0           return \@hashes;
34             }
35              
36             sub _pickuped_indexes {
37 0     0     my $self = shift;
38             $self->_indexes or sub {
39 0     0     my @indexes;
40 0           my $L = $self->L;
41 0           for my $i ( 0 .. $L - 1 ) {
42 0           my %seen;
43 0           while (1) {
44 0           my $rand = int( rand( $self->d * $SCALE ) );
45 0 0         if ( !$seen{$rand} ) {
46 0           $seen{$rand} = 1;
47 0 0         last if keys %seen == $self->k * $SCALE;
48             }
49             }
50 0           push( @indexes, [ sort { $a <=> $b } keys %seen ] );
  0            
51             }
52 0           $self->_indexes( \@indexes );
53             }
54 0 0         ->();
55             }
56              
57             sub _unarize {
58 0     0     my $self = shift;
59 0           my $vector = shift;
60 0           my $max = max(@$vector);
61 0           my $n = $SCALE / $max;
62 0           my @unary;
63 0           for (@$vector) {
64 0           my $i = int( $_ * $n );
65 0           my $j = $SCALE - $i;
66 0           for ( 1 .. $i ) {
67 0           push( @unary, 1 );
68             }
69 0           for ( 1 .. $j ) {
70 0           push( @unary, 0 );
71             }
72             }
73 0           return \@unary;
74             }
75              
76             1;
77             __END__