We realize that we can simplify the first loop if we simply subtract the first element from $original later:sub decode2 { my $total = shift; my $delta; my $diff; foreach (@_) { $delta += $_; $diff += $delta; } my $original= ($total-$diff)/(@_+1); my $value= $original; my @results= map { $value += $_ } @_; return ($original, @results); }
Now we realize we can rearrange the return if we include the $original in the map:sub decode2 { my $total = shift; my $diff; $diff += $_ for @_; my $original= ($total-$diff)/(@_+1) - $_[0]; my $value= $original; my @results= map { $value += $_ } @_; return ($original, @results); }
sub decode2 { my $total = shift; my $diff; $diff += $_ for @_; my $original= ($total-$diff)/(@_+1) - $_[0]; my $next; my @results= map { $next += $_ } $original, @_; return @results; }
This also lets us get rid of the intermediary @results array altogether.
Next we realize that we needn't shift off the total, because rather than summing everything into $diff first and subtracting that from $total later, we can simply turn the addition loop into a subtraction loop. For that, we have to flip the sign on the total. Note that not shifting off the total affects many locations in the code.sub decode2 { my $dc; $_[0] = -$_[0]; $dc -= $_ for @_; # subtract the sum of all elements from the firs +t my $original= $dc/@_ - $_[1]; my $next; return map { $next += $_ } $original, splice @_, 1; }
$dc is an inaccurate name of course.. the DC component for the values is actually $dc/@_ - but oh well.
Some logical cleanup: rather than declaring a new variable and splicing from @_, we can just modify the first value inplace. And thus, a massive cleanup later, we have____________sub decode2 { my ($dc, $next); $_[0] = -$_[0]; $dc -= $_ for @_; # subtract the sum of all elements from the firs +t $_[0] = $dc/@_ - $_[1]; return map { $next += $_ } @_; }
In reply to Re: Perl Drag Racing - sum/delta list
by Aristotle
in thread Perl Drag Racing - sum/delta list
by John M. Dlugosz
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |