如何获得的信件数组中的每个图案不可能性 [英] How to get every possibile pattern of an array of letters
问题描述
可能重复:结果
的是否有更好的方法做字符串的排列?
块引用>
可以说我有字母
ABCD
和我想在一个字符串,它是4个字母,这些字母的每一个可能的模式/组合。
<块引用>
AAAA
咩咩咩
畜牧业协会
daaa
ABAA
ACAA
ACAD
ABBA
块引用>
等。
我可以使用哪些循环或图案列出每个组合可以吗?
我在C#写这个,但它的实例在C ++和JavaScript亦欢迎。
我目前的想法只是增加每个字母可能的一个字母。然后向右移动一次并重复。这并不能掩盖状花纹。
ABBA
块引用>
解决方案您可以使用LINQ这样做很容易:
的String []项= {一,b,C,D};
VAR的查询= I1从在项目
选择I1 + I2 + I3 + I4中的项目
中的项目
项
从I2 I3从从0-14;
的foreach(VAR结果查询)
Console.WriteLine(结果);
如果你不提前知道你想要的四个组合的时候,可以计算任意笛卡尔产品具有更多的工作:
的 http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx
Possible Duplicate:
Are there any better methods to do permutation of string?Lets say I have the letters
a b c d
and I want to get every single possible pattern/combination of these letters in a string that is 4 letters long.
aaaa
baaa
caaa
daaa
abaa
acaa
acad
abba
and so on.
What loop or pattern can I use to list every combination possible?
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
解决方案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屋!