use List::Util qw/sum/; use Memoize; memoize('sum_to'); use strict; sub sum_to { # given : $n, @ary # return : two array refs, the first one summing to $n # the second one has the remaining elements # return nothing if it's impossible my $n = shift; my @ary = @_; return [[],\@ary] if $n==0; return if ($n<0 || @ary==0); for my $elem (@ary) { my %seen; my @left = grep { $_ != $elem || $seen{$_}++ } @ary; if (my $found = sum_to($n-$elem,@left)) { return [ [ $elem, @{ $found->[0] } ], [ @{ $found->[1] } ] ]; } } return; } my @nums = map int rand 1000, 1..100; my $sum = sum @nums; my $target = int ( $sum / 2); while ($target > 0) { my $found = sum_to($target,@nums) or next; my $first = $target ." == ". join '+', @{ $found->[0] }; my $second = ($sum-$target)." == ". join '+', @{ $found->[1] }; print join "\n",$first, $second; die "there was a problem" unless eval $first && eval $second; last; } continue { $target--; }