Suppose you have a list of numbers, presumably closely grouped. Instead of listing the numbers, you can list the total followed by the delta between each item and the previous (no delta listed for the first item).
It's a slight bit of algebra to figure out how to get the original list back, and I illustrated it with a Perl function. I used a couple foreach loops rather than map, because I wanted to make the math clear to non-Perl programmers.
Then I benchmarked it with a map instead, and found about 8% speedup.
So, how else might this function be improved, in terms of speed? I don't think it's possible without making two passes through the data. But, just like someone who doesn't know how to map is missing something, I wonder if there are any other techniques I can employ here.
sub decode2
{
my $total= shift;
my $delta= 0;
my $diff= 0;
foreach (@_) {
$delta += $_;
$diff += $delta;
}
my $original= ($total-$diff)/(1+scalar @_);
my $value= $original;
my @results= map {
$value += $_;
} @_;
return ($original, @results);
}
Test vector:
input: 5028 1 -21 44 -1
output: 1000 1001 980 1024 1023
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.