good chemistry is complicated,and a little bit messy -LW PerlMonks

### Re^2: partition of an array

by rir (Vicar)
 on Apr 22, 2009 at 04:19 UTC ( #759178=note: print w/replies, xml ) Need Help??

in reply to Re: partition of an array
in thread partition of an array

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

Replies are listed 'Best First'.
Re^3: partition of an array
by BrowserUk (Pope) on Apr 23, 2009 at 03:30 UTC
No, neither of us should do that. :-) I should have just well enough alone with my brute force solution.

I tested my "quick" version with every data set in this thread and more; and managed to miss sequences like: 550, 450, 360, 340, 300. Oh well, I'll be more perspicacious tomorrow. Ha!

Be well,
rir

Create A New User
Node Status?
node history
Node Type: note [id://759178]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (9)
As of 2020-10-01 18:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My favourite web site is:

Results (18 votes). Check out past polls.

Notices?