
use strict;
sub fudge_numbers {

        my $dp = shift;
        my ($tot,@pct,$tpct);

        # calculate total sum of inputs, store in $tot
        map { $tot += $_ } @_;
        
        # calculate percentages of inputs as float, store in @pct
        # this could be more (or less) explicit ;)
        map { 
                my $tmp = sprintf("%.".$dp."f",( ($_/$tot) * 100 ) );
                push(@pct,$tmp);
                } @_;
        
        # calculate relative diff
        map { $tpct += $_ } @pct;
        my $rdif = sprintf("%.".$dp."f",( 100 - $tpct ));
        
        # add $rdif to random item from @pct
        my $idx = rand(scalar(@pct));
        $pct[int($idx)] += $rdif;
        
        # return the pretty set as a list
        return @pct;    

        }
        

########### print test cases #############


my @testcases;
        
$testcases[0] = '1,100,100,100';         # 33.3, 33.4, 33.3
$testcases[1] = '0,100,100,100';         # 33, 34, 33
$testcases[2] = '2,100,100,100';         # 33.33, 33.34, 33.33
$testcases[3] = '2,7,7,7';                       # 33.33, 33.34, 33.33
$testcases[4] = '1,30,30,10';            # 42.9, 42.9, 14.2
$testcases[5] = '1,'.int(rand(100)); # 100
$testcases[5] = int(rand(7)).','.int(rand(100)).','.int(rand(100)).','.int(rand(100)).','.int(rand(100)).','.int(rand(100)).','.int(rand(100)); 


foreach(@testcases) {

        my @inputs = split(',',$_);

        my @fudge = fudge_numbers(@inputs);
        my $final_total;
        map { $final_total += $_ } @fudge;
        print "--\n";
        print "input: ".$_."\n";
        print "fudged nubmers : ".join(',',@fudge)."\n";
        print "final total : $final_total\n";   
        }
        print "--";
########### /print test cases #############


exit;

