Python Best fit algorithm -

2.7k Views Asked by At

I'm trying to wright a Best fit algorithm for bin-packing. Bin-packing problem: minimize the number of bins used for packing items, given a volume capacity.

What this heuristic should do is

  1. Try to place the item in the fullest bin that will accommodate it, i.e., the bin that will leave the least room left over

  2. If no bin is found, start a new bin.

To write this, I made an auxiliary volume. For the item you want to place, add the volume to each bin. The bin with the highest volume (that is still feasible) will get the item. I tried the following in Python:

item = ['a', 'b', 'c', 'd', 'e']
volume = [9,5,6,7,2]
V = 15

class Bin(object):
 def __init__(self):
    self.items = []
    self.sumVolume = 0
    self.auxvolumeSpace = 0

 def add(self, item, volume):
    self.items.append(item)
    self.sumVolume += volume
    self.auxvolumeSpace = self.sumVolume

 def __str__(self):
    # Printable representation
    return 'Bin(TotalVolume=%d, products=%s)' % (self.sumVolume, str(self.items))

if __name__ == '__main__':

def packAndShow(volume, maxVolume):

    bins = pack(volume, maxVolume)

    print('Solution using', len(bins), 'bins:')
    for i in bins:
        print(i)
    print('The total amount of bins needed, using the Best fit Algorithm is: ',len(bins))


def auxiliaryspace(volume, maxVolume):
 bins = []
 maxvolumespace = -1

 for bin in bins:
    if bin.sumVolume + volume <= maxVolume:
        bin.auxvolumeSpace += volume
        if bin.auxvolumeSpace >= maxvolumespace:
            maxvolumespace = bin.auxvolumeSpace
 return maxvolumespace


def pack(volume, maxVolume):
 bins = []
 for i in range(len(volume)):
    mv = auxiliaryspace(volume[i], maxVolume) 
    for bin in bins:
        if mv > 0 and bin.auxvolumeSpace == mv:
            bin.add(item[i], volume[i])
            break
    else:
        bin = Bin()
        bin.add(item[i], volume[i])
        bins.append(bin)

return bins


packAndShow(volume, V)

The problem is that the all items are placed in a new bin. The result is the following:

Solution using 5 bins:
Bin(TotalVolume=9, products=['a'])
Bin(TotalVolume=5, products=['b'])
Bin(TotalVolume=6, products=['c'])
Bin(TotalVolume=7, products=['d'])
Bin(TotalVolume=2, products=['e'])
The total amount of bins needed, using the Best fit Algorithm is:  5

I think the problem is somewhere in the "auxiliaryspace" part. I don't think the right value (that I want) is returned.. Can somebody please help?

0

There are 0 best solutions below