in reply to Divide array of integers into most similar value halves
I think that Dominus' book Higher Order Perl contains an example for something similar, and if I remember correctly it just went through all possible solutions, which doesn't scale very well for long lists.
Update: Here's a very simple approximative solution (after finding out that it might be good enough):
#!/usr/bin/perl use strict; use warnings; use List::Util qw(sum); divide(8,14,32,29); divide(7,10,12,15,40); sub divide { my @array = reverse sort { $a <=> $b} @_; my $target = sum(@array) / 2; my @result; my $current = 0; for (@array) { if ($current + $_ <= $target) { push @result, $_; $current += $_; } } print "@result\n"; print "Target: $target; Result: $current\n"; } __END__ 32 Target: 41.5; Result: 40 7 15 12 Target: 42; Result: 34
If that's not good enough you can iterate over all pairs of values from distinct sets and see if the reached value improves. If it does, swap these two elements.
(second update: fixed sort. FunkyMonk++)
|
|---|