in reply to Divide array of integers into most similar value halves
How about...
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Divide array of integers into most similar value halves
by JadeNB (Chaplain) on Sep 01, 2008 at 22:05 UTC | |
by FunkyMonk (Bishop) on Sep 01, 2008 at 22:29 UTC | |
by Pepe (Sexton) on Sep 02, 2008 at 02:57 UTC | |
|
Re^2: Divide array of integers into most similar value halves
by Pepe (Sexton) on Sep 02, 2008 at 03:58 UTC | |
by FunkyMonk (Bishop) on Sep 02, 2008 at 16:40 UTC | |
by Pepe (Sexton) on Sep 02, 2008 at 17:58 UTC | |
|
Re^2: Divide array of integers into most similar value halves
by Pepe (Sexton) on Sep 01, 2008 at 20:50 UTC |