I am searching for an algorithm to fill several slots, which are already filled to some level.
Examples http://img695.imageshack.us/img695/6529/fill.png
The image above shows six examples, each column represents a slot. The grey area is already filled, the blue are is the expected position of the new elements.
I could iterate through my slots and increase the quantity on the lowest slot by 1
until the available quantity is consumed, but I wonder about how to actually calculate the new filling levels.
I am going to implement this with SQL
/PL/SQL
, other code is just as welcome though :)
This is pretty straightforward.
You can visualize this as pouring water and let it fill, except for certain cases *.
You should be good.
This algorithm runs in O( n log n )
time.
*Some cases this doesn't make sense, but you would still want to do it anyhow:
#
#
##
###
###
In that case, you would fill the third column, then the first, then the second, but of course it's not quite filling water.
Perhaps a greedy algorithm with randomization to break ties will be sufficient.
Let n be the number of slots you need to fill.
Step 1: Loop through the columns to identify the columns that have the least no of filled up slots. Skip the columns that are already filled up.
Step 2: If no of columns are identified in step 1 is greater than one then choose one at random.
Step 3: Set n = n-1
Repeat steps 1, 2 and 3 till n = 0 or you do not have any empty columns.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With