2011-12-10 28 views
0

例子:VB.NET:生成的文件中的所有可能的話

如果得到消息「唐」,那麼文件將包含

ddd 
ddo 
ddn 
dod 
doo 
don 
dnd 
dno 
dnn 
odd 
odo 
odn 
ood 
<...> 

我也沒辦法做到這一點。不少於3個符號字。

+0

看這裏,有你 [StackOverflow上] [1] 的解決方案0 [1]:http://stackoverflow.com/questions/7853653/vb-net-all-combinations/7854261#7854261 – Martin

回答

1

我提出的專家交流,解決方案,你可能不能夠看到(如果你從來沒有祈禱,他們),所以我複製你:

問題是: 我有n個項目,每個項目都被分配一個1或2.所以我想得到矩陣結果,這將產生所有可能的組合。

例如,如果n = 3,那麼可能的結果是:我需要一個可以爲n生成這個序列的算法。請幫忙謝謝。我非常希望將結果存儲在一個DataTable

1 1 1 
1 1 2 
1 2 1 
2 1 1 
2 1 2 
1 2 2 
2 2 1 
2 2 2 

答:

Dim HighestValue As Integer = 2 ' max value 
    Dim NrOfValues As Integer = 3 ' nr of values in one result 
    Dim Values(NrOfValues) As Integer 
    Dim i As Integer 
    For i = 0 To NrOfValues - 1 
     Values(i) = 1 
    Next 
    Values(NrOfValues - 1) = 0 ' to generate first as ALL 1 
    For i = 1 To HighestValue^NrOfValues 
     Values(NrOfValues - 1) += 1 
     For j As Integer = NrOfValues - 1 To 0 Step -1 
      If Values(j) > HighestValue Then 
       Values(j) = 1 
       Values(j - 1) += 1 
      End If 
     Next 
     Dim Result As String = "" 
     For j As Integer = 0 To NrOfValues - 1 
      Result = Result & CStr(Values(j)) 
     Next 
     Debug.WriteLine(Result) 
    Next 

好這裏的解決方案,你只需要一個寫中的Debug.WriteLine更改爲您的文件

Dim HighestValue As Integer = 3 ' max value 
    Dim NrOfValues As Integer = 3 ' nr of values in one result 
    Dim Values(NrOfValues) As Integer 
    Dim i As Integer 
    For i = 0 To NrOfValues - 1 
     Values(i) = 1 
    Next 
    Values(NrOfValues - 1) = 0 ' to generate first as ALL 1 
    For i = 1 To HighestValue^NrOfValues 
     Values(NrOfValues - 1) += 1 
     For j As Integer = NrOfValues - 1 To 0 Step -1 
      If Values(j) > HighestValue Then 
       Values(j) = 1 
       Values(j - 1) += 1 
      End If 
     Next 
     Dim Result As String = "" 
     For j As Integer = 0 To NrOfValues - 1 
      If Values(j) = 1 Then Result = Result & "d" 
      If Values(j) = 2 Then Result = Result & "o" 
      If Values(j) = 3 Then Result = Result & "n" 
      'Result = Result & CStr(Values(j)) 
     Next 
     Debug.WriteLine(Result) 
    Next 
+0

如何使用此功能?我需要返回一個字符串。 –

+0

取出Debug.WriteLine(Result)中的字符串,其中包含e解決方案的值,將它們連接在一起,我只能給出算法,您必須根據需要調整它 – Martin

相關問題