Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

RE: Generating a Pattern

by fundflow (Chaplain)
on Jul 25, 2000 at 01:29 UTC ( #24194=note: print w/ replies, xml ) Need Help??


in reply to Generating a Pattern

Here's my version:

@a = (1); for (1..10) { print "@a\n"; @na=(); for (@a) { $na[-1] == $_ ? $na[-2]++ : push @na, (1, $_) } @a=@na; }
It does not move elements around (assuming push/pop are doing the natural thing) and has only one temporary copy.

Update: Use [-1] instead of [$#na]. Cool, learned a new thing!
Update: use ?: instead of if/then


Comment on RE: Generating a Pattern
Select or Download Code
RE: RE: Generating a Pattern
by eak (Monk) on Aug 06, 2000 at 07:58 UTC
    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)  
    

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://24194]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (13)
As of 2015-07-07 06:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (87 votes), past polls