Best Fit Algorithm
And now we come to our last algorithm, the
Best Fit Algorithm. The only difference between this and the
Worst Fit Algorithm is that instead of picking a Bin with the most amount of free space, this algorithm picks the Bin with the
least
amount of free space in it that can still hold the current
Element. The results you obtain by using this algorithm are not
always the same as the Worst Fit, sometimes it is slightly better,
other times it is not. It depends on the nature of the data
supplied.
Private Sub BestFit()
If Elements Is Nothing Then Exit Sub
Dim ElementsCopy(Elements.GetUpperBound(0)) As Integer
ReDim Bins(0)
Dim BinNumber, BinElement, BinCount As Integer
Dim BestBin, BestBinAmount As Integer
Dim i, j, k As Integer
DeepCopyArray(Elements, ElementsCopy)
If Me.Decreasing = True Then
Array.Sort(ElementsCopy)
Array.Reverse(ElementsCopy)
End If
ReDim Bins(0)(0)
For i = 0 To ElementsCopy.GetUpperBound(0)
BestBin = -1
BestBinAmount = -1
For j = 0 To BinNumber
BinElement = Bins(j).GetUpperBound(0)
BinCount = 0
For k = 0 To BinElement
BinCount += Bins(j)(k)
Next
If BestBinAmount < BinCount AndAlso BinCount + ElementsCopy(i) <= Me.BinHeight Then
BestBinAmount = BinCount
BestBin = j
End If
Next
If BestBin = -1 Then
ReDim Preserve Bins(BinNumber + 1)
BinNumber += 1
ReDim Bins(BinNumber)(1)
BinElement = 0
Bins(BinNumber)(BinElement) = ElementsCopy(i)
Else
BinElement = Bins(BestBin).GetUpperBound(0)
ReDim Preserve Bins(BestBin)(BinElement + 1)
Bins(BestBin)(BinElement) = ElementsCopy(i)
End If
Next
For i = 0 To BinNumber
For j = 0 To Bins(i).GetUpperBound(0)
If Bins(i)(j) = 0 Then
ReDim Preserve Bins(i)(j - 1)
End If
Next
Next
GC.Collect()
End Sub
With the same set of data as the last example, this algorithm will lay out something like this in memory: