This is a combinatorial problem I think in essence, but I'm not interested in the number of combinations rather how to get them. If I'm working with a number of arrays (stored in an AoA or whatever data structure you want, but I think AoA is best) I need to return the sum of the elements of each combination of the arrays. I can do NC2 but I can't seem to figure out how to get up to NC3 let alone NCN with an algorithm (which is what I'm hoping someone can help me with) (All arrays in the AoA are the same size, hence my use of @$AoA[0] for size in the 3rd for loop) Here's NC2:
#!/usr/bin/perl use strict; use warnings; my @newAoA; my @AoA = ( [1,1,1],[0,0,0],[1,0,1],[0,0,1] ); my $arrRef = $AoA[0]; my $c = 0; for (my $i = 0; $i < scalar @AoA ; $i++){ for (my $j =$i+1; $j< scalar @AoA ; $j++){ for (my $k=0; $k< scalar @$arrRef; $k++){ ### scalar @$AoA[0] +doesn't work, maybe im losing my mind but thats the same as @$arrRef push @{$newAoA[$c]}, ($AoA[$i][$k] + $AoA[$j][$k]); } $c++; } } foreach my $array (@newAoA){ print @$array,"\n"; } foreach my $array (@newAoA){ print @$array,"\n"; }
prints:
111 212 112 101 001 102

edit: sorry, I was a bit rusty too much java lately *sigh*. This code works


In reply to adding combinations of arrays (of arrays) by aquinom

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.