in reply to Re^5: Divide array of integers into most similar value halves
in thread Divide array of integers into most similar value halves
It's obviously not the best algorithm, and I rushed the implementation.
use strict; use warnings; use Algorithm::Loops qw( NextPermuteNum ); use List::Util qw( sum ); my @nums = @ARGV; my $sum = sum @nums; my @best = @nums; my $best; @nums = sort { $a <=> $b } @nums; do { my $p = $sum; my $q = 0; for my $i (0..$#nums) { my $x = $nums[$i]; $p -= $x; $q += $x; my $diff = abs($p-$q); if (!defined($best) || $best > $diff) { $best = $diff; @best = ( [ @nums[ 0 .. $i ] ], [ @nums[ $i+1 .. $#nums ] ], ); } } } while ( NextPermuteNum(@nums) ); my @p = @{ $best[0] }; print(sum(@p), ": ", join('+', @p), "\n"); my @q = @{ $best[1] }; print(sum(@q), ": ", join('+', @q), "\n");
>perl script.pl 8 14 32 29 40: 8+32 43: 14+29 >perl script.pl 7 10 12 15 40 44: 7+10+12+15 40: 40
I'm not clear on the complexity of NextPermuteNum — I have a cold that is making me very tired — so maybe my analysis is wrong.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^7: Divide array of integers into most similar value halves
by moritz (Cardinal) on Sep 01, 2008 at 20:50 UTC |