http://www.perlmonks.org?node_id=1228506


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.