我正在尝试编写一个单词组合生成器,我的意思是打印“X”个字符数与“X”字符串长度的所有可能组合,
首先,我需要说的是,我在 StackOverFlow 中看到了一个关于这个问题的问题,其中有很多单词生成器的答案来执行此操作(在不同的语言上),但是请不要将其标记为重复或不要评论我的问题只是为了引用我该链接,因为我已经测试了该问题的所有 C# 和 VBNET 代码,实际上没有一个能够 100% 按预期工作,请参阅我需要的组合:
例如,如果我有“a”、“b”和“c”字符,并且我想将这些字符的所有组合放入“3”长度的字符串中,那么这就是我期望的结果:
' Expected result, 27 combinations:
'
' aaa
' aab
' aac
'
' aba
' abb
' abc
'
' aca
' acb
' acc
'
' baa
' bab
' bac
'
' bba
' bbb
' bbc
'
' bca
' bcb
' bcc
'
' caa
' cab
' cac
'
' cba
' cbb
' cbc
'
' cca
' ccb
' ccc
(排序并不重要,我可以稍后排序。)
...但到目前为止,我能得到的预期结果是:
'a
'aa
'aaa
'b
'bb
'bbb
'c
'cc
'ccc
我之前已经用两种语言(Ruby 和 Batch)完成了这次操作,但是使用嵌套的 Fors(很多 Fors 在一起,每个 Fors 只附加一个字母到另一个 For 输出),当然,如果我尝试在 VBNET 中执行此操作,避免很多Fors的起诉,并且以更好的表现方式来做。
在下面的代码中,您可以看到我如何尝试在 RAM 内存(数组)中分配所有组合,而不是将它们写入物理磁盘,因此我想使用逻辑方法并以更好的性能方式编写此代码,然后我想首先将所有组合保存在“内存中”,这也是我不想使用大量 for(性能)的原因。
这是我最后一次尝试,所有内容都在注释行中进行了解释:
Public Class Form1
Dim characters As Char() ' Default value: {"a","b","c"}
Dim StringLength As Int64 ' Default value: 3
Dim TotalCombinations As Int64 ' Default value: 27
Dim strarray(99999999) As String ' Default size: "99.999.999" million of combinations in memory (I need to confirm this from an expert).
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim index As Int64 = 0
For column As Int64 = 0 To TotalCombinations - 1 ' For 0 to 26
For Each character As Char In characters ' Characters = {"a","b","c"}
If column < index Then
index = 0 ' I reset index value 'cause... just experimenting things.
Try
strarray(index) += characters(index)
RichTextBox1.Text += strarray(index) & ControlChars.NewLine
Catch
End Try
Else
Try
strarray(index) += characters(index)
RichTextBox1.Text += strarray(index) & ControlChars.NewLine
Catch
End Try
End If
Next
index += 1
Next
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
characters = sender.text.ToCharArray ' Result: {"a","b","c"}
Calculate_Combinations() ' Result: 27
End Sub
Private Sub NumericUpDown1_ValueChanged(sender As Object, e As EventArgs) Handles NumericUpDown1.ValueChanged
StringLength = sender.value ' Result: 3
Calculate_Combinations() ' Result: 27
End Sub
Private Sub Calculate_Combinations()
Try
TotalCombinations = ((characters.LongLength * StringLength) * StringLength) ' Result: 27
Label1.Text = ((characters.LongLength * StringLength) * StringLength) & " number of combinations." ' Result: 27
Catch : End Try
End Sub
End Class
我精确的帮助。