What is an efficient algorithm for randomly assigning a pool of objects to a parent using specific rules

Posted by maple_shaft on Programmers See other posts from Programmers or by maple_shaft
Published on 2012-09-12T20:02:00Z Indexed on 2012/09/12 21:49 UTC
Read the original article Hit count: 145

Filed under:
|

I need some expert answers to help me determine the most efficient algorithm in this scenario.

Consider the following data structures:

type B { A parent; }

type A {
   set<B> children;
   integer minimumChildrenAllowed;
   integer maximumChildrenAllowed;
}

I have a situation where I need to fetch all the orphan children (there could be hundreds of thousands of these) and assign them RANDOMLY to A type parents based on the following rules.

  1. At the end of the job, there should be no orphans left
  2. At the end of the job, no object A should have less children than its predesignated minimum.
  3. At the end of the job, no object A should have more children than its predesignated maximum.
  4. If we run out of A objects then we should create a new A with default values for minimum and maximum and assign remaining orphans to these objects.
  5. The distribution of children should be as evenly distributed as possible.
  6. There may already be some children assigned to A before the job starts.

I was toying with how to do this but I am afraid that I would just end up looping across the parents sorted from smallest to largest, and then grab an orphan for each parent.

I was wondering if there is a more efficient way to handle this?

© Programmers or respective owner

Related posts about algorithms

Related posts about efficiency