如何获得一系列字母的每种可能模式 [英] How to get every possible pattern of an array of letters
问题描述
可能重复:
有没有更好的方法来排列字符串?
假设我有字母
abcd
a b c d
我希望在一个4个字母长的字符串中得到这些字母的每一个可能的模式/组合。
and I want to get every single possible pattern/combination of these letters in a string that is 4 letters long.
aaaa
aaaa
baaa
caaa
daaa
abaa
acaa
acad
abba
等等。
我可以用什么循环或模式列出每种可能的组合?
What loop or pattern can I use to list every combination possible?
我用C#写这个,但是例子在C ++和JavaScript中也是受欢迎的。
I am writing this in C#, but examples in C++ and javascript are welcome as well.
我目前的想法只为每个字母增加一个字母。然后向右移动一次并重复。这不包括类似的模式。
My current idea only increments one letter for each letter possible. Then shifts to the right once and repeats. This doesn't cover patterns like.
abba
abba
推荐答案
您可以使用LINQ轻松完成:
You can do so very easily with LINQ:
string[] items = {"a", "b", "c", "d"};
var query = from i1 in items
from i2 in items
from i3 in items
from i4 in items
select i1 + i2 + i3 + i4;
foreach(var result in query)
Console.WriteLine(result);
如果你事先不知道你想要四个的组合,你可以任意计算笛卡尔积更多的工作:
If you don't know ahead of time that you want the combinations of four, you can compute arbitrary Cartesian Products with a bit more work:
http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product- with-linq.aspx
这篇关于如何获得一系列字母的每种可能模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!