如何将所有可能的组合写入控制台?例如,如果用户输入abc,那么它将写入aaa,aab,aac,abb,abc,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
必须在虚线后删除不需要的排列以省略有效组合。
答案 0 :(得分:1)
def go(chars,thusfar):
if len(thusfar) = len(chars):
print thusfar
for char in chars:
go(chars,thusfar+char);
这应该很容易转换为VB(阅读:我不知道VB)
答案 1 :(得分:1)
您可以使用附加参数 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)
答案 2 :(得分:0)
你只需要在那里进行递归调用。
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
请注意,如果有人输入负数,您的代码将永久运行。我会把这个作为一个简单的练习。
答案 3 :(得分:0)
来自here:的惊人代码
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