VB.NET:生成文件中所有可能的单词

时间:2011-12-10 14:58:54

标签: vb.net combinations

示例:

如果得到了一句话,那么就不要说#34;然后文件将包含

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

我不知道这样做。不少于3个符号字。

1 个答案:

答案 0 :(得分:1)

我在Experts Exchange中提出了一个解决方案,您可能无法看到(如果您从未付过它们),所以我会为您复制它:

问题是: 我有n个项目,每个项目可以分配1或2.所以我想得到矩阵结果,这将产生所有可能的组合。

例如。如果n = 3,则可能的结果是:我需要一个可以为n生成此系列的算法。请帮助谢谢。理想情况下,我想将结果存储在数据表中

 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

Ok这是解决方案,您只需要通过写入文件来更改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