CSDN博客

img xubo8219

组合的算法(二)

发表于2008/9/28 12:19:00  139人阅读

 组合算法的另外一种实现:

Option Explicit

Dim sValue()     As String, fValue()       As Integer, bUsed()       As Boolean

Sub Initialize()
        Dim iLoop     As Integer
        ReDim fValue(UBound(sValue))
        ReDim bUsed(UBound(sValue))
        For iLoop = 0 To UBound(sValue)
                fValue(iLoop) = CDbl(sValue(iLoop))
                bUsed(iLoop) = False
        Next iLoop
End Sub

Function FindResult(fTotal As Double) As Boolean
        Dim iBit     As Integer, fTemp       As Single
        FindResult = False
        Do
                iBit = 0
                Do While iBit <= UBound(bUsed)
                        bUsed(iBit) = Not bUsed(iBit)
                        If bUsed(iBit) Then Exit Do
                        iBit = iBit + 1
                Loop
                If iBit > UBound(bUsed) Then Exit Function
                fTemp = 0
                For iBit = 0 To UBound(bUsed)
                        If bUsed(iBit) Then fTemp = fTemp + fValue(iBit)
                Next iBit
                If Abs(fTemp - fTotal) < 0.01 Then
                        FindResult = True
                        Exit Function
                End If
        Loop
End Function


Function GetResult() As String
        Dim iLoop     As Integer
        GetResult = " "
        For iLoop = 0 To UBound(bUsed)
                If bUsed(iLoop) Then
                        If GetResult <> " " Then GetResult = GetResult + "   +   "
                        GetResult = GetResult & CStr(fValue(iLoop))
                End If
        Next iLoop
End Function

Private Sub search_Click()
        Const sData = "1,1,1,1"
        Dim bResult     As Boolean, iCount       As Integer
        sValue = Split(sData, ",")
        Initialize
        iCount = 0
        Do
                bResult = FindResult(2)
                If bResult Then
                        iCount = iCount + 1
                        Debug.Print "Answer   " & iCount & "   is   :   " & GetResult()
                End If
        Loop While bResult
        End
End Sub

 

参考链接

http://topic.csdn.net/u/20070322/20/9b1e5b48-5282-4efe-bd15-d84413ea9042.html

0 0

相关博文

我的热门文章

img
取 消
img