. , , , . , . , .
, , . (m credits n debits m * n . , , )
http://en.wikipedia.org/wiki/Bin_packing_problem
. , , . , , . , , , , .
, , , .. , , , , , , /, .
$5.00 -> $2.66, $1.50
$3.55 -> $2.55
$1.55 -> $1.33
Public Type Record
ID As Long
Amount As Currency
Allocated As Boolean
AllocatedAmount As Currency
End Type
Public Function PaymentAllocation()
Dim cr() As Record
Dim de() As Record
' function returns records with amounts in descending order
cr = QueryToArray("CR", "CR_AMT")
de = QueryToArray("DE", "DE_AMT")
' first fit descending order
' starting with largest credit and debit, check if they fit
' if fit, then allocate
' if not, then check next credit
Dim i As Long, j As Long
For i = LBound(cr) To UBound(cr)
For j = LBound(de) To UBound(de)
If de(j).Allocated = False Then
If (cr(i).Amount - cr(i).AllocatedAmount) >= de(j).Amount Then
de(j).Allocated = True
cr(i).AllocatedAmount = cr(i).AllocatedAmount + de(j).Amount
Debug.Print cr(i).Amount, de(j).Amount
End If
End If
Next
Next
End Function
Public Function QueryToArray(tableName, fieldName) As Record()
Dim rs As Recordset
Dim ans() As Record
Dim i As Long
Set rs = CurrentDb.OpenRecordset("SELECT * FROM " & tableName & " ORDER BY " & tableName & "_AMT DESC;", dbOpenDynaset)
ReDim ans(1 To DCount(tableName & "_ID", tableName))
i = 0
Do Until rs.EOF
i = i + 1
ans(i).ID = rs(tableName & "_ID").Value
ans(i).Amount = rs(fieldName).Value
ans(i).Allocated = False
rs.MoveNext
Loop
rs.Close
Set rs = Nothing
QueryToArray = ans
End Function