I have a list of numbers and I want to add up all the different combinations. For example:
This Perl program seems to do what you want. It goes through the different ways to choose n items from k items. It's easy to calculate how many combinations there are, but getting the sums of each combination means you have to add them eventually. I had a similar question on Perlmonks when I was asking How can I calculate the right combination of postage stamps?.
The Math::Combinatorics module can also handle many other cases. Even if you don't want to use it, the documentation has a lot of pointers to other information about the problem. Other people might be able to suggest the appropriate library for the language you'd like to you.
#!/usr/bin/perl
use List::Util qw(sum);
use Math::Combinatorics;
my @n = qw(1 4 7 13);
foreach my $count ( 2 .. @n ) {
my $c = Math::Combinatorics->new(
count => $count, # number to choose
data => [@n],
);
print "combinations of $count from: [" . join(" ",@n) . "]\n";
while( my @combo = $c->next_combination ){
print join( ' ', @combo ), " = ", sum( @combo ) , "\n";
}
}