如何获得一个ArrayList的所有组合? [英] how to get all combination of an arraylist?
本文介绍了如何获得一个ArrayList的所有组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串ABCDE一个ArrayList
我想的方法与给定ArrayList的所有可能的组合返回另一个数组列表:在C#
I have an arraylist of strings "abcde" I want to a method to return another arraylist with all the possible combination of a given arraylist (ex:ab,ac,ad...) in C#
任何人都知道一个简单的方法是什么?
anyone knows a simple method?
注:长度为2的所有可能的组合,并且会更好,如果长度是可变(可改变)
NB: all possible combinations of length 2, and would be better if the length is variable(can be changed)
推荐答案
修饰您的评论需要长度两者的组合:
Pertaining your comment requiring combinations of length two:
string s = "abcde";
var combinations = from c in s
from d in s.Remove(s.IndexOf(c), 1)
select new string(new[] { c, d });
foreach (var combination in combinations) {
Console.WriteLine(combination);
}
在回答您的编辑任意长度:
Responding to your edit for any length:
static IEnumerable<string> GetCombinations(string s, int length) {
Guard.Against<ArgumentNullException>(s == null);
if (length > s.Length || length == 0) {
return new[] { String.Empty };
if (length == 1) {
return s.Select(c => new string(new[] { c }));
}
return from c in s
from combination in GetCombinations(
s.Remove(s.IndexOf(c), 1),
length - 1
)
select c + combination;
}
用法:
string s = "abcde";
var combinations = GetCombinations(s, 3);
Console.WriteLine(String.Join(", ", combinations));
输出:
abc, abd, abe, acb, acd, ace, adb, adc, ade, aeb, aec, aed, bac, bad, bae, bca,
bcd, bce, bda, bdc, bde, bea, bec, bed, cab, cad, cae, cba, cbd, cbe, cda, cdb,
cde, cea, ceb, ced, dab, dac, dae, dba, dbc, dbe, dca, dcb, dce, dea, deb, dec,
eab, eac, ead, eba, ebc, ebd, eca, ecb, ecd, eda, edb, edc
这篇关于如何获得一个ArrayList的所有组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文