How about...
- @numbers = reverse sort @numbers
- $target = sum(@numbers)/2
- loop forever {
- find largest $number in @numbers that is smaller than $target
- exit loop if not found
- add that number to @bucket
- remove that number from @numbers
- subtract that number from $target
- }
- return @bucket and @numbers
and in perl 5.10...
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 @b = split_evenly( \@numbers );
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;
}
replace the says with print for perl < 5.10.
Tested, but not exhaustively. Use at your own risk. etc.
Update: changed the output so the lists are displayed.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.