in reply to Re: partition of an array
in thread partition of an array
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.
Be well,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]; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: partition of an array
by BrowserUk (Patriarch) on Apr 23, 2009 at 03:30 UTC | |
by rir (Vicar) on Apr 23, 2009 at 20:25 UTC |