在數(shù)學(xué)的統(tǒng)計分支里,排列與組合是一個很重要的分支。在各種實際應(yīng)用中,排列與組合也扮演了重要的角色。舉例來說,安排人員參加活動可以看作是組合的應(yīng)用。比方說,現(xiàn)在有十個人,選出其中的五個人參加某項集體活動。由于彼此之間有著脾氣性格等因素,所以,不同的人員組合有著不同的工作效率?,F(xiàn)在,要求你找出效率最高的人員安排。因為選出五人參加活動,沒有順序問題,因此是一個組合的問題。如果說,隨機的選出一個組合,用計算機來實現(xiàn)是非常簡單的,常見的“洗牌算法”就能實現(xiàn)。要找出效率最高的組合,只要遍歷所有的組合即可。問題是如何遍歷所有的組合。 還是利用數(shù)學(xué)知識,我們知道組合函數(shù)C(m,n)代表著從n個人選m個人的組合的可能數(shù)。那么C(5,10)=252就表示本題有252種選擇。如果,給每一種組合都標(biāo)上標(biāo)號,不同的標(biāo)號代表不同的組合,這樣遍歷所有的組合就轉(zhuǎn)化為遍歷標(biāo)號了。 基于這個思想,完成下面的代碼。其中,主函數(shù)有兩個。 一個是 Public Shared Function C(ByVal C1 As Integer, _ ByVal C2 As Integer) As Integer 用來計算組合數(shù)的,C1是上標(biāo),C2是下標(biāo)。 另一個是 Public Shared Function GetCombination( _ ByVal Lower As Integer, _ ByVal Upper As Integer, _ ByVal Count As Integer, _ ByVal Index As Integer) As Integer() 這是根據(jù)參數(shù)返回一個組合, Lower表示返回組合的下限 Upper表示返回組合的上限 Count表示組合中的元素數(shù) Index表示該組合的標(biāo)號 要獲得一個組合,直接調(diào)用即可。如: Dim T() as Integer T= GetCombination(1,10,5,20) 這個表示返回本題的一個組合,其中20是標(biāo)號 如果想隨機得到一個組合,只要給一個隨機的標(biāo)號即可 要遍歷組合,設(shè)置參數(shù)I即可。如: Dim T() as Integer,I as Integer For I=1 to C(5,10) T=GetCombination(1,10,5,I) DoSomeWork 執(zhí)行根據(jù)組合計算效率的代碼 Next 這樣,就遍歷了所有的組合 代碼賦予其后,用的是VB2005 Public Class clsCombination Public Shared Function GetCombination( _ ByVal Lower As Integer, _ ByVal Upper As Integer, _ ByVal Count As Integer, _ ByVal Index As Integer) As Integer() If Count > Upper - Lower + 1 Then Return Nothing If Count <= 0 Then Return Nothing If Lower > Upper Then Return Nothing If Lower < 0 OrElse Upper < 0 Then Return Nothing Dim tS() As String = GetC(Lower, Upper, Count, Index) _ .Split(",".ToCharArray, _ StringSplitOptions.RemoveEmptyEntries) Dim tI() As Integer ReDim tI(tS.GetUpperBound(0)) Dim i As Integer For i = 0 To tI.GetUpperBound(0) tI(i) = tS(i) Next Return tI End Function Private Shared Function GetC(ByVal Lower As Integer, _ ByVal Upper As Integer, _ ByVal Count As Integer, _ ByVal Index As Integer) As String Dim i As Integer, tS As String If Count = Upper - Lower + 1 Then tS = "" For i = Lower To Upper tS &= i & "," Next Return tS End If Index = Index Mod C(Count, Upper - Lower + 1) i = C(Count - 1, Upper - Lower) If Index < i Then tS = Lower & "," & _ GetC(Lower + 1, Upper, Count - 1, Index) Else tS = GetC(Lower + 1, Upper, Count, Index - i) End If Return tS End Function Public Shared Function C(ByVal C1 As Integer, _ ByVal C2 As Integer) As Integer If C1 < 0 OrElse C1 > C2 OrElse C2 <= 0 Then Return 0 If C1 = 0 Then Return 1 Dim i As Integer, S1 As Single = 1 For i = 1 To C1 S1 *= (C2 - i + 1) / i Next Return S1 End Function End Class 本文來自CSDN博客,轉(zhuǎn)載請標(biāo)明出處:http://blog.csdn.net/grenet/archive/2009/09/29/4615779.aspx VB控件大全屬性詳解 組合框 http://wenku.baidu.com/view/8d35a869a45177232f60a21a.html VB第四章 常用控件 http://www.doc88.com/p-90693914376.html 廣州電視大學(xué)VB教程 http://vb./wlkj/xxfd_zdfd.html |
|