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.
- At the end of the job, there should be no orphans left
- At the end of the job, no object A should have less children than its predesignated minimum.
- At the end of the job, no object A should have more children than its predesignated maximum.
- 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.
- The distribution of children should be as evenly distributed as possible.
- 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?
EDIT:
Expanding upon the criteria for even distribution of children, we should attempt to avoid a situation where any one A has 2 or more children than any other A unless they started that way. For example, if A1 has 4 children, and A2 and A3 have 1 child each and there are 2 orphans, then A2 and A3 should each be assigned an orphan making an even distribution of 4, 3, and 3 children for each A.
Yes I understand we could end up where there is one orphan left and an A that has not met its minimum. This exception case will be handled by a separate algorithm that will try to evenly split an A into two objects and assign the remaining orphans amongst them.
EDIT: 2
Ok, I misunderstood the requirements in my situation. The data model for A shows minimum and maximum property but in fact this should be a global setting for every A. In essence it is a missed requirement that requires the data model to be refactored later.
All A will have the same minimum and maximum now. This actually changes things significantly! Sorry for the confusion.