Home > front end >  Filling Algorithm for Equal Distribution
Filling Algorithm for Equal Distribution

Time:12-04

Need your help resolving algorithm task - There are 3 baskets, basket 1 has 10 balls and a possible max capacity of 100, basket 2 has 50 balls and a possible max capacity of 200, and basket 3 has 100 balls and a possible max capacity of 300. Please help me to write an algorithm or code that split another 100 balls between the 3 baskets for the best possible equal distribution between the baskets. Not possible to move balls between the baskets.

Your suggested algorithm should of course work on any number of baskets with different max capacities and any onHand value, for example, 1 ball that I want to add or the maximum capacity value that should fill all baskets to 100% fill.

CodePudding user response:

As already mentioned in one of my comments. If you want to have an equal distribution of %fill, then you could add the balls individually to the current lowest filled basket:

import numpy as np

def fill_baskets(baskets, ballsToDistribute):
    for i in range(ballsToDistribute, 0, -1):
        # find the basket with the lowest percentage of balls in it
        currFillLevels = [currFill / maxFill for currFill, maxFill in baskets]
        minIndex = np.argmin(currFillLevels)

        # give the ball to this basket
        baskets[minIndex][0]  = 1

    return baskets


baskets = [[10, 100], [50, 200], [100, 300]]

new_baskets = fill_baskets(baskets, 100)

# print the result:
for i, basket in enumerate(new_baskets):
    print(f"Basket {i 1}: {basket[0]/basket[1]:.3f}% ({basket[0]}/ {basket[1]})")

The output I get for this case if the following:

Basket 1: 0.440% (44/ 100)
Basket 2: 0.435% (87/ 200)
Basket 3: 0.430% (129/ 300)

The only problem that can arise from the code is when we have too many balls to give away. Then all the baskets will be overfilled.

  • Related