First Fit Algorithm
Now let's talk about an algorithm with a little more "intelligence". The
First Fit Algorithm
does exactly as its name implies. It steps through the Elements
sticking them into the first Bin it can, if there aren't any Bins that
it will fit into, a new Bin is added. You will get pretty
efficient use of Bins with this algorithm.
Private Sub FirstFit()
If Elements Is Nothing Then Exit Sub
Dim ElementsCopy(Elements.GetUpperBound(0)) As Integer
ReDim Bins(0)
Dim BinNumber, BinElement, BinCount 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)
Dim bPlaced As Boolean = False
For j = 0 To BinNumber
BinElement = Bins(j).GetUpperBound(0)
BinCount = 0
For k = 0 To BinElement
BinCount += Bins(j)(k)
Next
If BinCount + ElementsCopy(i) <= Me.BinHeight Then
ReDim Preserve Bins(j)(BinElement + 1)
Bins(j)(BinElement) = ElementsCopy(i)
bPlaced = True
Exit For
Else
End If
Next
If bPlaced = False Then
ReDim Preserve Bins(BinNumber + 1)
BinNumber += 1
ReDim Bins(BinNumber)(1)
BinElement = 0
Bins(BinNumber)(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: