So I'm actually going to use this to do some dynamic form layout generation in ExtJS4, but I think I can simplify the problem down to facilitate discussion without losing anything:
Let's say I have a list of integers that I want to place inside two containers. When I'm done I want both containers to be "as even as possible", which in this case means the sums of the integers inside each container are as close to each other as we can get them. In this scenario it doesn't matter how many integers end up in each container, simply that their sums are close.
Here's an example of a possible input and a desirable output:
Integers: [1,7,13,3,6,8]
Container A: [13,6] (sum 19)
Container B: [1,7,3,8] (sum 19)
One naive approach might be to iterate over the integer list once, and put the each integer in the container that currently has the smaller sum:
Integers: [1,7,13,3,6,8]
Container A: [1,13,8] (sum 22)
Container B: [7,3,6] (sum 16)
What algorithm / approach would you guys suggest for tackling this problem? I imagine there are quite a few potential ones. If you find it easier to think in code samples I'll be implementing the end product in javascript.
Thanks!
EDIT
I like the two approaches presented so far (thanks cheeken and sumudu fernando), both of which give good methods for quickly achieving something close to (or exactly) the ideal answer. For a small enough set of integers I imagine you could just brute force a calculation and definitively say that the particular answer is the best (or tied for best). Any suggestions for doing something like that? In other words, an approach that guarantees an ideal answer at the cost of potentially being slow (or completely infeasible for large problem sets).
s
.s
.