Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Re: Sum of N elements in an M element array

by Corion (Pope)
on Feb 01, 2020 at 09:11 UTC ( #11112220=note: print w/replies, xml ) Need Help??

in reply to Sum of N elements in an M element array

There are many simple ways to do this. I would look at Data::PowerSet to generate sets of all numbers to sum, or program it myself by using the binary digits of a counter to indicate whether an element should be included:

00000 # (no element summed) 00001 # e 00010 # d 00011 # d+e 00100 # c ... 11111 # a+b+c+d+e

What code have you written and where do you have problems?

Replies are listed 'Best First'.
Re^2: Sum of N elements in an M element array
by abhay180 (Sexton) on Feb 02, 2020 at 07:56 UTC
    Thanks Corion. The exact problem is about finding all the combinations. I find Math:Combinatorics useful as well. Here is what i did to gather all 2-item combinations from N item array. I wasn't sure how i would do it for any M items.
    @a=(1..5); my @comb=""; for(my $i=0;$i<=$#a;$i++) { for(my $j=0;$j<=$#a;$j++) { next if $i==$j; if ($a[$i] < $a[$j]) { push @comb, "$a[$i] , $a[$j]" ; } else { push @comb, "$a[$j] , $a[$i]" ; } } } shift @comb; use List::MoreUtils qw(uniq); @comb = uniq(@comb);
      Thanks all for your suggestions. I managed w Math:Combinatorics to get what i want.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (5)
As of 2020-06-07 10:56 GMT
Find Nodes?
    Voting Booth?
    Do you really want to know if there is extraterrestrial life?

    Results (42 votes). Check out past polls.