But! it looks like FunkyMonk's code doesn't get the best partition always:

use List::Util qw(sum); use List::MoreUtils qw(first_index); #my @numbers = map { rand() * 100 } 1 .. 5; #my @numbers = (8,14,32,29); my @numbers = @ARGV; my @b = split_evenly( \@numbers ); sub say { print @_,"\n" } say "First container: sum(@{$b[0]}) = ", sum @{$b[0]}; say "Second container: sum(@{$b[1]}) = ", sum @{$b[1]}; sub split_evenly { my @numbers = reverse sort { $a <=> $b } @{+shift}; my $target = sum(@numbers) / 2; say "Target is $target"; my @b; while ( 1 ) { my $index = first_index { $_ <= $target } @numbers; last if $index < 0; $target -= $numbers[$index]; push @b, splice @numbers, $index, 1; } return \@b, \@numbers; }
perl funky.pl 400 402 521 735 758 191 307 679 776 877 Target is 2823 First container: sum(877 776 758 402) = 2813 Second container: sum(735 679 521 400 307 191) = 2833

but a better partition is

First container: sum(400 402 521 735 758) = 2816 Second container: sum(191 307 679 776 877) = 2830

update: ah, of course. That is what your "Difference" output field reveals....


In reply to Re^2: NP-complete sometimes isn't (A benchmark) by shmem
in thread NP-complete sometimes isn't by tilly

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.