CR18 has asked for the wisdom of the Perl Monks concerning the following question:
In my text file/data file, I have -1 1 7 -4 3 -51 4 47 -87 (randomly placed) top to bottom. So, it read as a column.use strict; my @array = @ARGV ? @ARGV : qw( -1 1 7 -4 3 -51 4 47 -87); #****************************************** #\sorting the array from small to large # HERE @array = ( @array ); @array = sort { $a <=> $b } @array; #****************************************** #\ my $sumAll=0; for (@array){ #\sum of all numbers HERE sumAll $sumAll +=$_; } my $cur = my $best_start = my $best_end = my $cur_start = 0; my $sumPos = $array[0]; for (0..$#array) { $cur += $array[$_]; if ($sumPos < $cur) { $sumPos = $cur; $best_start = $cur_start; $best_end = $_; } if ($cur < 0) { $cur = 0; $cur_start = $_ + 1; } } my $sumNeg = $sumAll-$sumPos; #\Sum of negative[sumNeg] = sumAll-s +umPos print qq(Start: $best_start End: $best_end Numbers: @array[$best_start..$best_end]\n\n Order of Array: @array Sum of All: $sumAll Sum of positive: Chr1, $sumPos Sum of Negative: Chr1, $sumNeg );
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: calculate sum of numbers inside a text file
by davido (Cardinal) on Sep 27, 2015 at 03:06 UTC | |
by CR18 (Initiate) on Sep 27, 2015 at 05:01 UTC | |
by CR18 (Initiate) on Sep 27, 2015 at 05:58 UTC | |
by davido (Cardinal) on Sep 27, 2015 at 06:16 UTC | |
by parv (Parson) on Sep 27, 2015 at 08:51 UTC | |
|
Re: calculate sum of numbers inside a text file
by Athanasius (Archbishop) on Sep 27, 2015 at 07:35 UTC | |
|
Re: calculate sum of numbers inside a text file
by 1nickt (Canon) on Sep 27, 2015 at 02:14 UTC | |
by CR18 (Initiate) on Sep 27, 2015 at 04:32 UTC |