I'm using a stack algorithm to solve a combinatorial problem--and I'm out of my comfort zone. This simplified example finds the subsets of a set of integers whos sum is a target number.

Searches on 'perl perl stack' or 'perl perl subset' proved rather off-topic, and 'combinatorial algorithm' was way out there. So I'm hoping for some constructive criticism here. For starters, is there a better/faster than brute-force algorithm? Or how about a more Perlish implementation? I feel like a C programmer ;p

Here's the code I'm using now.

use strict; my @block = qw/ 1 2 3 4 5 6 7 8 9 /; my $target = 20; my @solutions = solve($target,@block); print join(',',@$_) . "\n" for ( @solutions ); # find all combinations of blocks that sum to target sub solve { my ( $target, @block ) = @_; my ( @solutions, @trial, @stack ); my $acc = -1; NEW: while (1) { if ( sum( \@trial ) == $target ) { my @solu = @trial; push @solutions, \@solu; } OLD: while (1) { $acc++; if ( $acc <= $#block ) { push @trial, $block[$acc]; push @stack, $acc; next NEW; } elsif (@stack) { pop @trial; $acc = pop @stack; next OLD; } else { last NEW } } } return @solutions; } sub sum { local $_; my ($array) = @_; my $sum; $sum += $_ for (@$array); return $sum; }
TIA!

--Solo

Update: fixed a small code typo

--
You said you wanted to be around when I made a mistake; well, this could be it, sweetheart.

In reply to Better algorithm than brute-force stack for combinatorial problems? by Solo

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.