Are your lists big? And do you really need the best solution, or is a good approximation sufficient?

I think that Dominus' book Higher Order Perl contains an example for something similar, and if I remember correctly it just went through all possible solutions, which doesn't scale very well for long lists.

Update: Here's a very simple approximative solution (after finding out that it might be good enough):

#!/usr/bin/perl use strict; use warnings; use List::Util qw(sum); divide(8,14,32,29); divide(7,10,12,15,40); sub divide { my @array = reverse sort { $a <=> $b} @_; my $target = sum(@array) / 2; my @result; my $current = 0; for (@array) { if ($current + $_ <= $target) { push @result, $_; $current += $_; } } print "@result\n"; print "Target: $target; Result: $current\n"; } __END__ 32 Target: 41.5; Result: 40 7 15 12 Target: 42; Result: 34

If that's not good enough you can iterate over all pairs of values from distinct sets and see if the reached value improves. If it does, swap these two elements.

(second update: fixed sort. FunkyMonk++)


In reply to Re: Divide array of integers into most similar value halves by moritz
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.