Here is the loop structure to your problem:

use strict; my @list = (-25, 14, 50, 20, -7, -8, -10); my @result = (); my $sum; for my $elem (@list) { for (@{[@result]}) { push @result, [ @$_, $elem ]; $sum = eval join '+' => @{$result[-1]}; print join(',', @{$result[-1]}), "\n" unless $sum; } push @result, [ $elem ]; print $elem, "\n" unless $elem; }

Result:

-25,50,-7,-8,-10

You will need some additional work in order to obtain array indexes instead of values.

How it works:

  • In first pass, it will ignore the inner for and it will push [ -25 ] into @result. Result is [ [-25] ]
  • In second pass, it will push 14 into a copy of what it already has, and then it will push [ 14 ]. Result is: [ [-25], [-25,14], [14] ]
  • In second pass, it will push 50 into a copy of what it already has, and then it will push [ 50 ]. Result is: [ [-25], [-25,14], [14], [-25,50], [-25,14,50], [14,50], [50] ]
  • While it does that, it will print whatever combinations that sum zero.
  • That's it!


    In reply to Re: permutation algorithm by fglock
    in thread permutation algorithm by Basilides

    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.