algorithm to sum up a list of numbers for all combinations

前端 未结 15 2281
北荒
北荒 2020-12-04 22:34

I have a list of numbers and I want to add up all the different combinations. For example:

  • number as 1,4,7 and 13
  • the output would be:

15条回答
  •  生来不讨喜
    2020-12-04 23:27

    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";
            }
        }
    

提交回复
热议问题