It's obviously not the best algorithm, and I rushed the implementation.

use strict; use warnings; use Algorithm::Loops qw( NextPermuteNum ); use List::Util qw( sum ); my @nums = @ARGV; my $sum = sum @nums; my @best = @nums; my $best; @nums = sort { $a <=> $b } @nums; do { my $p = $sum; my $q = 0; for my $i (0..$#nums) { my $x = $nums[$i]; $p -= $x; $q += $x; my $diff = abs($p-$q); if (!defined($best) || $best > $diff) { $best = $diff; @best = ( [ @nums[ 0 .. $i ] ], [ @nums[ $i+1 .. $#nums ] ], ); } } } while ( NextPermuteNum(@nums) ); my @p = @{ $best[0] }; print(sum(@p), ": ", join('+', @p), "\n"); my @q = @{ $best[1] }; print(sum(@q), ": ", join('+', @q), "\n");
>perl script.pl 8 14 32 29 40: 8+32 43: 14+29 >perl script.pl 7 10 12 15 40 44: 7+10+12+15 40: 40

I'm not clear on the complexity of NextPermuteNum — I have a cold that is making me very tired — so maybe my analysis is wrong.


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