生成前X个排列 [英] Generating first X number of permutations
问题描述
我已经尝试了很多方法,但我无法弄清楚如何生成,例如给定字符数组时的前10个排列。
我正在寻找的是:
chars ='abcd'
count = 10
输出应为:
a
b
c
d
aa
ab
ac
ad
ba
bb
有没有简单的方法来实现这个目标? />
我的尝试:
-------- -------------------------------------------------- -----------------------------
I've tried so many methods but I just can't figure out how to generate, for example the first 10 permutations when given a character array.
What I'm looking for is this:
chars = 'abcd'
count = 10
The output should then be:
a
b
c
d
aa
ab
ac
ad
ba
bb
Is there a simple way to achieve this?
What I have tried:
---------------------------------------------------------------------------------------
推荐答案
见这里:< a href =https://stackoverflow.com/questions/756055/listing-all-permutations-of-a-string-integer> c# - 列出字符串/整数的所有排列 - Stack Overflow [< a href =https://stackoverflow.com/questions/756055/listing-all-permutations-of-a-string-integertarget =_ blanktitle =New Window> ^ ]
是一个简单的方法来实现这个目标吗?
Is there a simple way to achieve this?
是的,但在40个问题之后,你应该知道我们不做你的功课。
Yes, but after 40 questions, you should know that we don't do your homework.
例如前10个排列
您的示例输出不是排列!
Your sample output is not a permutation!
正如我之前提到的那样(解决方案已被删除 - 在您看来 - 与问题无关),您想要获得的结果不是排列 [ ^ ]。
如果您有兴趣实现产生序列集的方法,
基于解决方案#1中提供的链接 OriginalGriff [ ^ ],我已将Linq C#GetPermutations
方法转换为VB .NET表单:
As i mentioned it earlier (solution has been deleted as it was - in your opinion - unrelated to the question), a result you want to get is not a permutation[^].
If you are interested to implement method which produces set of sequences,
Based on the link provided in solution#1 by OriginalGriff[^], i've translated Linq C#GetPermutations
method into VB.NET form:
Sub Main
Dim chars As String = "ABCD"
Dim count = 10
'get 10 permutations of ABCD arranged into 3-part sequences
Dim result = GetPermutations(chars.ToArray(), 3).Take(count)
For Each r In result
Console.WriteLine("{0}", String.Join("", r))
Next
End Sub
Function GetPermutations(Of T)(list AS IEnumerable(Of T), length As Integer) AS IEnumerable(Of IEnumerable(Of T))
If length = 1 Then Return list.Select(Function(o) New T(){o})
Return GetPermutations(list, length - 1) _
.SelectMany(Function(a) list.Where(Function(e) Not a.Contains(e)), Function(t1, t2) t1.Concat(New T(){t2}))
End Function
以上代码产生10个结果,例如:
Above code produces 10 results, for example:
ABC
ABD
ACB
ACD
ADB
ADC
BAC
BAD
BCA
BCD
如果你想获得N部分的结果,你需要改进上面的代码:
In case you want to get a result of N-part, you need to improve above code:
For i = 1 To chars.Length
Dim result = GetPermutations(chars.ToArray(), i).Take(count)
For Each r In result
Console.WriteLine("{0}", String.Join("", r))
Next
Next
如果你想获得非Linq解决方案,你必须实现自己的交换
和 GetPer
SO提供的方法。
If you want to get non-Linq solution, you have to implement your own Swap
and GetPer
methods provided on SO.
这篇关于生成前X个排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!