in reply to Re^2: Divide array of integers into most similar value halves
in thread Divide array of integers into most similar value halves

Take a look at moritz's orginal reply and its followups. That's the difference between doing it correctly (their discussion) and an evil, dirty, quick hack (my version).

It all depends with how bad "good enough" can be :)

My program will never allow the first container to hold more than $target. All the other numbers go into the second. With (41,37,37,43) as input, 43 goes into the first container, and none of the other numbers will fit, so all the rest go into the second container.

Tweaking the comparison in first_index will allow this dataset to be divided more evenly, but will produce worse solutions in some cases. For example, making this change

first_index { $_ <= $target*1.1 } # allow container to overflow by 10%

produces (I changed the output format slightly):

Original numbers: (41 37 37 43) Target is 79 First container: sum(43 37) = 80 Second container: sum(41 37) = 78

The code is fast, so there's nothing to stop you dividing your numbers twice using the untweaked and tweaked comparison and choosing the answer you like best.

But, all that does is make a dirty, evil, quick hack dirtier, more evil and slower. You'll still be able to find cases where it fails.

The only real solution is to do it properly.


Unless I state otherwise, all my code runs with strict and warnings

Replies are listed 'Best First'.
Re^4: Divide array of integers into most similar value halves
by Pepe (Sexton) on Sep 02, 2008 at 17:58 UTC
    Thanks FunkyMonk!!!
    I already fixed the problem (hopefully) by doing one more iteration of the loop and checking if the difference between subarrays were smaller. Your suggestion is maybe better in terms of time. I'm trying it now.
    It's a great script anyway. Thank's a lot. It's important for me to make this work, but not to spend days in the calculations.