I first have to say that I really enjoyed this problem. It took me a little while to come up with a working algorithm, unfortunately it wasn't at elegant as yours. I thought I would play with your version to see if I could improve upon it a bit. The only thing I could do was add the use of references which reduces the memcopy time on larger lists. Below is a script that benchmarked the old 'non_ref' vs. the new 'ref'. Not necessarily staggering, but an improvement. I compacted the for loop for flipping it around and putting the for statement at the end of the conditional line.
#!/usr/bin/perl
use Benchmark;
my $count = 100;
my $end = 30;
sub ref {
my $a = [1];
for(1..$end){
# print "@$a\n";
my @na;
($na[-1] == $_ ? $na[-2]++ : push @na, (1, $_)) for @$a;
$a = \@na;
}
}
sub no_ref {
my @a = (1);
my @na;
for (1..$end){
# print "@a\n";
@na = ();
($na[-1] == $_ ? $na[-2]++ : push @na, (1, $_)) for @a;
@a = @na;
}
}
timethese($count, { 'no_ref' => \&no_ref , 'ref' => \&ref} );
Benchmark: timing 100 iterations of no_ref, ref...
no_ref: 11 wallclock secs (11.12 usr + 0.04 sys = 11.16 CPU)
ref: 9 wallclock secs ( 8.34 usr + 0.06 sys = 8.40 CPU)
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.