#!/usr/bin/perl -w

use 5.032;

my @list; 
push @list, rand()*10_000 for (1..1000);

my $r = isbenford(@list);

say "Not conclusive!" if $r == -1;
say (($r>0) ? "YES" : "NO") if $r > -1;

my @list2;
my $c = 0;
for my $i (1..9){
     for (my $j = int 90/(1+log10($i)); $j>=$i*10; $j--){   # ERROR
	 $list2[$c++] = $i;
     }
}

my $r2 = isbenford(@list2);

say "Not conclusive!" if $r2 == -1;
say (($r2>0) ? "YES" : "NO") if $r2 > -1;

my $r3 = isbenford2(@list2);

say "Not conclusive!" if $r3 == -1;
say (($r3>0) ? "YES" : "NO") if $r3 > -1;

exit 1;


sub isbenford {
    my @l = @_;
    my @digits;
    for (@l){
	/^(\d)/;
	if (defined $1){
	    $digits[$1]++;
	}else{
	    warn "not a digit first: $_";
	}
    }
    my ($one, $two, $three) = (0,0,0);
    for (1..9){                        # esto lo dividí por mis oo, pero podría ser 1-3, 4-6, 7-9
	next unless defined $digits[$_]; 
	if ($_ < 3){
	    $one += $digits[$_];
	}elsif ($_ > 7){
	    $three += $digits[$_];
	}else{
	    $two += $digits[$_];
	}
    }
    if ($one > $two && $two > $three){
	return 1;
    }elsif (($one < $two && $two > $three) || ($three > $one)){
	return 0;
    }else{
	return -1;
    }
}

sub isbenford2 {
    my @l = @_;
    my @digits;
    for (@l){
	/^(\d)/;
	if (defined $1){
	    $digits[$1]++;
	}else{
	    warn "not a digit first: $_";
	}
    }
    my ($one, $two, $three) = (0,0,0);
    for (1..9){                        # 1-3, 4-6, 7-9
	next unless defined $digits[$_]; 
	if ($_ <= 3){
	    $one += $digits[$_];
	}elsif ($_ < 7){
	    $two+= $digits[$_];
	}else{
	    $three += $digits[$_];
	}
    }
    if ($one > $two && $two > $three){
	return 1;
    }elsif (($one < $two && $two > $three) || ($three > $one)){
	return 0;
    }else{
	return -1;
    }
}


sub log10 {
    my $x = shift;
    return (log $x/log 10);
}


__END__
  
Experimental Benford test. It's not in any way conclusive,
  by the implementation and by itself. If "YES" numbers are ok,
  if "NO" you could suspect.  

  


