This sounds like a good dynamic programming exercise :
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--; }
I think this might fail in the case where there are two ways to sum to a given number, and only one of those ways is right -- to account for this, sum_to shd probably return an array of solutions.

In reply to Re: Divide array of integers into most similar value halves by bduggan
in thread Divide array of integers into most similar value halves by Pepe

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.