Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re^2: Perl ARRAY() result

by kschwab (Vicar)
on Jan 14, 2019 at 13:37 UTC ( [id://1228530]=note: print w/replies, xml ) Need Help??


in reply to Re: Perl ARRAY() result
in thread Perl ARRAY() result

It does look more elegant and compact, but it's significantly slower:
$ perl ./thescript
Benchmark: timing 1000 iterations of orig, tybalt89...
     orig:  3 wallclock secs ( 2.48 u + 0.00 s =  2.48 CPU) @403.23/s (n=1000)
 tybalt89: 10 wallclock secs (10.22 u + 0.00 s = 10.22 CPU) @ 97.85/s (n=1000)
#!/usr/bin/perl use strict; use warnings; use Benchmark qw(timethese); sub solve1 { my ( $goal, $elements ) = @_; my ( @results, $RecursiveSolve, $nextValue ); $RecursiveSolve = sub { my ( $currentGoal, $included, $index ) = @_; for ( ; $index < @$elements ; ++$index ) { $nextValue = $elements->[$index]; if ( $currentGoal > 2 * $nextValue ) { $RecursiveSolve->( $currentGoal - $nextValue, [ @$included, $nextValue ], $index + 1 ); } else { if ( $currentGoal == $nextValue ) { push @results, [ @$included, $nextValue ]; } return if $nextValue >= $currentGoal; } } }; $RecursiveSolve->( $goal, [], 0 ); undef $RecursiveSolve;#Avoid memory leak from circular reference return @results; } sub solve2 { my $want = shift() or return []; $want > 0 or return (); my ( $first, @rest ) = @{ shift() } or return (); map( [ $first, @$_ ], solve2( $want - $first, \@rest ) ), solve2( $want, \@rest ); } my @results; my @tosolve=(869,[15,43,51,56,60,67,122,152,193,204,229,271,293,301]); timethese( 1000, { 'orig' => sub { solve1(@tosolve) }, 'tybalt89' => sub { solve2(@tosolve) } } );

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (3)
As of 2024-04-25 12:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found