Code:
#!/usr/bin/perl
use Math::Combinatorics;
my @nums = qw(-10 -8 -12 7 5 4 3 1 9);
for my $i (0..@nums-1) {
for my $j (1..@nums) {
my $combinat = Math::Combinatorics->new(
count => $j,
data => [@nums[1..$#nums]]
);
while (my @combo = $combinat->next_combination) {
if (sum(@combo) == $nums[0]) {
print $nums[0] . " = " . join(" + ", @combo);
print "\n";
}
}
}
@nums = rotate(@nums);
}
sub sum {
my $sum = 0;
foreach my $i (@_){
$sum += $i if $i == int($i);
}
return $sum;
}
sub rotate {
my @array = @_;
return (@array[1..$#array], $array[0]);
}
Brute force method in Perl. You'll need the Math::Combinatorics package from CPAN.
On your data set: -10, -8, -12, 7, 5, 4, 3, 1, 9
It produces:
-10 = 3 + -12 + -8 + 7
-10 = -12 + -8 + 1 + 9
-10 = -12 + 5 + 4 + 1 + -8
-8 = 4 + -12
-8 = 1 + 3 + -12
-8 = 5 + 9 + -12 + -10
-8 = 7 + -10 + 4 + -12 + 3
-8 = -10 + 9 + 4 + 1 + -12
-12 = -8 + -10 + 5 + 1
7 = 4 + 3
7 = -10 + 3 + 9 + 5
7 = 1 + -8 + 9 + 5
7 = 4 + 1 + 3 + 9 + -10
7 = 4 + 1 + 9 + -12 + 5
5 = 4 + 1
5 = -8 + 9 + 4
5 = -8 + 3 + 9 + 1
5 = 9 + -12 + 7 + 1
5 = 3 + 1 + 9 + 4 + -12
5 = 3 + 1 + -10 + 4 + 7
5 = 7 + 3 + -8 + 9 + -10 + 4
4 = 1 + 3
4 = -12 + 7 + 9
4 = -8 + 5 + 7
4 = -8 + 3 + 9
4 = 5 + -10 + 9
4 = 1 + -12 + 3 + 7 + 5
4 = 5 + 3 + -12 + 9 + 7 + -8
4 = 5 + 1 + 9 + -10 + 7 + -8
3 = 7 + -8 + 4
3 = 9 + -10 + 4
3 = 7 + 1 + -10 + 5
3 = 9 + 1 + -12 + 5
3 = 9 + -8 + -10 + 5 + 7
3 = 4 + 1 + 9 + 7 + -10 + -8
3 = 4 + 9 + 7 + -10 + -12 + 5
1 = -8 + 9
1 = 5 + -8 + 4
1 = 7 + -10 + 4
1 = -12 + 9 + 4
1 = -10 + -8 + 9 + 7 + 3
1 = -8 + 5 + 9 + -12 + 7
1 = 4 + 3 + -10 + 9 + -12 + 7
1 = 4 + 3 + -10 + -8 + 5 + 7
1 = 4 + 3 + 9 + -8 + 5 + -12
9 = 4 + 5
9 = 5 + 3 + 1
9 = -8 + 7 + 4 + 1 + 5
9 = 7 + 4 + -10 + 3 + 5
EDIT: No code tag...if you paste it into Emacs and use the indent every line feature it'll show up nicely.