in reply to Re^10: Divide array of integers into most similar value halves
in thread Divide array of integers into most similar value halves
Okay. Try this version.
In most tests I've run, a limit of 10* the number of elements finds the optimum even for large arrsys of widely spaced numbers.
Most of my tests having been run using a custom shuffle that uses Math::Random::MT, but that was mostly to achieve repeatability. I see no reason that you will not see similar results using your native rand() and List::Util::shuffle().
sub partition { my( $limit, $aRef ) = @_; my @in = sort{ $a <=> $b } @$aRef; my $target = sum( @in ) >> 1; my( $best, @best ) = 9e99; my $soFar = 0; my @half; for( 1 .. $limit ) { # printf "%6d : [@half] [@in] [@best]\n", abs( $soFar - $target + ) if $V; $soFar += $in[ 0 ], push @half, shift @in while $soFar < $targ +et; return( \@half, \@in ) if $soFar == $target; my $diff = abs( $soFar - $target ); ( $best, @best ) = ( $diff, @half ) if $diff < $best; $soFar -= $half[ 0 ], push @in, shift @half while $soFar > $ta +rget; return( \@half, \@in ) if $soFar == $target; $diff = abs( $soFar - $target ); ( $best, @best ) = ( $diff, @half ) if $diff < $best; srand( $_ ); shuffle @in; } my %seen; $seen{ $_ }++ for @best; return \@best, [ grep{ --$seen{ $_ } < 0 } @$aRef ]; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^12: Divide array of integers into most similar value halves
by Pepe (Sexton) on Sep 04, 2008 at 21:02 UTC | |
by BrowserUk (Patriarch) on Sep 04, 2008 at 21:26 UTC | |
by BrowserUk (Patriarch) on Sep 04, 2008 at 21:33 UTC | |
by Pepe (Sexton) on Sep 04, 2008 at 21:54 UTC | |
by BrowserUk (Patriarch) on Sep 04, 2008 at 22:28 UTC | |
by Pepe (Sexton) on Sep 04, 2008 at 22:46 UTC | |
|