Math::Combinatorics helps with generating the combinations.
use strict; use warnings; use Math::Combinatorics; my @array = (6, 18, 12, 2, 49); my @sums = (30, 18); for my $target (@sums) { for (1..@array) { my @combs = Math::Combinatorics::combine ($_, @array); for my $comb (@combs) { my $sum = 0; map {$sum += $_} @$comb; next if $sum != $target; print "$target = " . (join " + ", @$comb) . "\n"; } } }
30 = 12 + 18 18 = 18 18 = 12 + 6
In reply to Re: finding values in an array that add up to a specific number
by GrandFather
in thread finding values in an array that add up to a specific number
by Forsaken
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |