Worst Fit Algorithm
Despite its name, the
Worst Fit Algorithm produces result that are consistently better than the
First Fit Algorithm.
This does come with some extra processing though (on small data sets it
doesn't really matter). The only difference between the two
algorithms is that Worst Fit picks the Bin with the most amount of free
space (or creates a new Bin if no existing one can fit the Element)
instead of just picking the first Bin available.
Private Sub WorstFit()
If Elements Is Nothing Then Exit Sub
Dim ElementsCopy(Elements.GetUpperBound(0)) As Integer
ReDim Bins(0)
Dim BinNumber, BinElement, BinCount As Integer
Dim WorstBin, WorstBinAmount 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)
WorstBin = -1
WorstBinAmount = Me.BinHeight + 1
For j = 0 To BinNumber
BinElement = Bins(j).GetUpperBound(0)
BinCount = 0
For k = 0 To BinElement
BinCount += Bins(j)(k)
Next
If WorstBinAmount > BinCount AndAlso BinCount + ElementsCopy(i) <= Me.BinHeight Then
WorstBinAmount = BinCount
WorstBin = j
End If
Next
If WorstBin = -1 Then
ReDim Preserve Bins(BinNumber + 1)
BinNumber += 1
ReDim Bins(BinNumber)(1)
BinElement = 0
Bins(BinNumber)(BinElement) = ElementsCopy(i)
Else
BinElement = Bins(WorstBin).GetUpperBound(0)
ReDim Preserve Bins(WorstBin)(BinElement + 1)
Bins(WorstBin)(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: