tags:

views:

231

answers:

3

Let's say I have a list of numbers:

2,2,3,4,4

Split the numbers into N groups (3 groups here as an example):

A:2,3 sum:5

B:4 sum:4

C:2,4 sum:6

What I want is to minimize (the group with the highest sum (6 here) - the group with the smallest sum (4 here))

Does anyone think of an algorithm to achieve this?

Another example:

7,7,8,8,8,9,9,10

The result should be as follows:

A:7,8,8 sum:23

B:7,8,9 sum:24

C:9,10 sum:19

+1  A: 

Considering that even if N is two the problem is NP complete, I can give you a very bad algorithm.

http://mathworld.wolfram.com/NumberPartitioningProblem.html

MSN
+5  A: 

Unfortunately, this problem is NP hard. See references for multiprocessor scheduling or bin packing. You may also be able to find some useful approximation algorithms, if you're interested in that approach.

zweiterlinde
A: 

Zweiterlinde's suggestion to check out bin packing is the way to go.

I went ahead and posted this, having realized it was wrong after I had typed it all.

You want a greedy approach where the largest numbers are used first.

  1. sort the list to achieve an ordering
  2. Begin placing the largest numbers into groups -- as many as will fit to reach the first number
  3. Stop when max number of groups is reached
  4. Sort your groups by sum and repeat by adding the largest number to the smallest group, repeating until done.

This should get you: from 2,2,3,4,4 ...

group 1 (4): 4
group 2 (6): 4, 2
group 3 (5): 3, 2

and from 7,7,8,8,8,9,9,10 ...

group 1 (18): 10, 8
group 2 (24): 9, 8, 7
group 3 (24): 9, 8, 7

Though I guess the second example could be done as 19, 24, 23 which makes this wrong. Hmph.

Nerdling
This breaks down when there are big gaps in the numbers. Consider splitting (10,1,1,1,1,1,1,1,1) into two groups. Your algorithm outputs (10,1,1,1,1),(1,1,1,1) while the correct answer is (10),(1,1,1,1,1,1,1,1).
Welbog
yup. realized after i typed it all and figured I'd just send it out anyways
Nerdling
Well, anyway, the problem is NP-complete so if your algorithm worked you'd be a million dollars richer. ;)
Welbog
Yup! and out of a potential grad school thesis.However, dynamic programming would help here either way.
Nerdling
My friend asked me this questsion.It seems easy at first glance, but actually it doesn't easy.
Billy