For the universe of positive integers, I sensed a simple solution lurking. I found one but I didn't like how it
coded up: It was just pushing the largest onto a half,
if it was forced onto the currently smaller half, put it
in a
protest queue in that half. When ready to add a number to the other half in the presence of a protest, you would instead pop the top of the queue to the other half. This works and is fairly efficient but it is messy in the control code.
Today, it just struck me that you don't have to keep the halves abs( @left - @right) <= 1 as you create them;
just make sure there is enough remaining to fill the other half.
use List::Util qw{ sum };
sub L() { 0} # left
sub R() { 1} # right
sub remainder_halves {
my $in = shift;
my $ar ;
@$ar = sort { $b <=> $a } @$in;
die "bounds error" if @$ar && $$ar[-1] < 0;
my @ans = ( [], [] ); # halves for answer
no warnings 'uninitialized'; # summing empty arrays
my ( $targ, $other ) = ( L, R );
my ( $halfsize) = int((@$ar+1)/2);
while ( @$ar ) {
while ( sum( @{$ans[$targ]}) <= sum( @{$ans[$other]})
&& @{$ans[$targ]} < $halfsize
) {
push @{$ans[$targ]}, shift @$ar;
}
( $targ, $other ) = ( $other, $targ);
push @{$ans[$targ]}, shift @$ar if @{$ans[$targ]} < $halfsize;
}
my $score = abs( sum( @{ $ans[L] } ) - sum( @{ $ans[R] } ) );
return $score, $ans[L], $ans[R];
}
Be well,
rir
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.