Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re^2: Perl ARRAY() result

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


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

Here's pme's changes as the whole script.
use strict; use warnings; sub Solve { 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 ) { #print join( ',', @$included, $nextValue ), "\n"; push @results, [ @$included, $nextValue ]; } return if $nextValue >= $currentGoal; } } }; $RecursiveSolve->( $goal, [], 0 ); undef $RecursiveSolve; # Avoid memory leak from circular refere +nce return @results; } my @results = Solve( 869, [ 15, 43, 51, 56, 60, 67, 122, 152, 193, 204, +229, 271, 293, 301 +] ); foreach my $result (@results) { print join(',',@$result),"\n"; }

Replies are listed 'Best First'.
Re^3: Perl ARRAY() result
by stevieb (Canon) on Jan 14, 2019 at 02:08 UTC

    Absolutely brilliant!

    ++ and kudos for denoting a circular reference :)

      Oh, I didn't do anything here other than merge pme's changes with the original post and fix the formatting a little.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (5)
As of 2024-03-28 17:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found