问题描述
|
如何将所有可能的组合写入控制台?例如,如果用户输入abc,则它将写入aaa,aab,aac,abb,abc,acc,acc,bbb,bbc,ccc。请帮我。
这是一些代码:
Dim abc() As String = {\"a\",\"b\",\"c\"} \'
Sub Main()
Console.WriteLine(\"Enter the amount of characters\")
Dim count As Integer = Console.ReadLine
outputStrings(\"\",count)
Console.ReadLine()
End Sub
Private Sub outputStrings(ByVal startString As String,ByVal letterCount As Integer)
For i = 0 To abc.Length - 1
Dim temp As String = startString
temp += abc(i)
If temp.Length = letterCount Then
Console.WriteLine(temp)
If i = abc.Length - 1 Then
Console.WriteLine(\"----\")
End If
Else
outputStrings(temp,letterCount)
End If
Next
End Sub
在虚线后必须执行某些操作以删除不必要的排列,从而仅保留有效的组合。
解决方法
您可以使用附加参数abcIndex将用于abc(i)或右侧的字母限制为字母,然后从此处开始for循环。只写字母按字母顺序排列的字符串,以防止重复。
Private Sub outputStrings(ByVal startString As String,ByVal letterCount As Integer,ByVal abcIndex As Integer)
For i = abcIndex To abc.Length - 1
Dim temp As String = startString
temp += abc(i)
If temp.Length = letterCount Then
Console.WriteLine(temp)
Else
outputStrings(temp,letterCount,i)
End If
Next
End Sub
致电:
outputStrings(\"\",3,0)
,def go(chars,thusfar):
if len(thusfar) = len(chars):
print thusfar
for char in chars:
go(chars,thusfar+char);
这应该足够容易地转换为VB(阅读:我不知道VB)
,您只需要在那里进行递归调用。
Dim abc() As String = {\"a\",\"b\",\"c\"} \'
Sub Main()
Console.WriteLine(\"Enter the amount of characters\")
Dim count As Integer = Console.ReadLine
outputStrings(\"\",count)
Console.ReadLine()
End Sub
Private Sub outputStrings(ByVal startString As String,ByVal letterCount As Integer)
For i = 0 To abc.Count - 1
Dim temp As String = startString
temp += abc(i)
If temp.Length = letterCount Then
Console.WriteLine(temp)
Else
outputStrings(temp,letterCount)
End If
Next
End Sub
请注意,如果有人输入负数,则您的代码将永远运行。我将通过简单的练习来解决该问题。
,来自这里的惊人代码:
Private Shared Function PermutationsWithRepetition(Of T)(list As IEnumerable(Of T),length As Integer) As IEnumerable(Of IEnumerable(Of T))
If length = 1 Then
Return list.[Select](Function(x) New T() {x})
End If
Return PermutationsWithRepetition(list,length - 1).SelectMany(Function(x) list,Function(t1,t2) t1.Concat(New T() {t2}))
End Function
可以与Integer,Char,Double等一起使用。
使用示例:
Dim myarray(1) As Integer
myarray(0) = 1
myarray(1) = 2
Dim k As Integer = 2 \'number of \"slots\" to do the permutations
mypermutations = PermutationsWithRepetition(myarray,k)
For Each row As IEnumerable(Of Integer) In mypermutations
Console.WriteLine(\"\")
For Each col As IntegerIn row
Console.Write(col.toString())
Next
Next
输出:
11
12
21
22