Friday, August 19, 2011

How to evenly distribute a set to 2 parts


A few years ago I came acrross this problem. I had to evenly distribute a set of databases (of different sizes) on 2 servers, so that each server would be evenly loaded. After some thinking I came up with the following simple algorithm and afterwards proved it to be correct.


The algorithm

In the beginning we have - 1 set of items, 2 empty groups (into which the items will be distributed)

1. Sort the set by the size of its items, descending
2. Take the first item out of the set and put it in the group whose items have the smaller sum of values (or if they are equal in any one)
3. Repeat 2. while there are items in the set

Pseudocode

function distributeSet (set, group1, group2)
{
   order set descending;

   var sum1 = 0, sum2 = 0;

   while (set not empty)
   {
      var item = next item from set;

      if (sum1 <= sum2)
      {
          add item to group1;
          sum1 = sum1 + item.value;
      }
      else
      {
          add item to group2;
          sum2 = sum2 + item.value;
      }
   }
}

The proof

This algorithm can be prooved by using the mathematical induction.

We have a (descending) ordered set of items and two groups.

(1) The items in the two groups are evenly distributed in the beginning, because the groups are empty.
(2) 
a) Assume that the items in the groups are evenly distributed
b) We add the first item from the set, which is smaller or equal than any other in the groups (because the set is ordered descending), to the group that is currently smaller (let's call this group - A, and the other one - B). Before adding the item to A, we are sure that A <= B (smaller or equal). Now there are 2 possible cases:
(i) After adding the item to A, it is still A <= B and
(ii) it is A > B.
In case of (i) the items are for sure evenly distributed because the relationship of the sizes of the groups remains the same.
If in case of (ii) the items were not evenly distrubuted, and they would be evenly distribued if we put the item in group B, we would have increased the difference between the sizes of A and B. And because the set was ordered there is no item in B that is smaller than the current item that we could move to A to make the distribution even. Therefor in case of (ii) the items are also evenly distributed.

According to the mathematical induction we can conclude on the basis of (1) and (2) that this way of distributing the items into the groups is even.

No comments:

Post a Comment