当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - how to get all combination of an arraylist?

问题描述:

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?

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;
}

Usage:

string s = "abcde";
var combinations = GetCombinations(s, 3);
Console.WriteLine(String.Join(", ", combinations));

Output:

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
网友答案:

Here is my generic function which can return all the combinations of type T:

static IEnumerable<IEnumerable<T>> GetCombinations<T>(IEnumerable<T> list, int length)
{
    if (length == 1) return list.Select(t => new T[] { t });

    return GetCombinations(list, length - 1)
        .SelectMany(t => list, (t1, t2) => t1.Concat(new T[] { t2 }));
}

Usage:

Console.WriteLine(
    string.Join(", ",
        GetCombinations("abcde".ToCharArray(), 2).Select(list => string.Join("", list))
    )
);

Output:

aa, ab, ac, ad, ae, ba, bb, bc, bd, be, ca, cb, cc, cd, ce, da, db, dc, dd, de, ea, eb, ec, ed, ee

UPDATED Please see my answer here for other scenarios, e.g. permutations and k-combinations etc.

分享给朋友:
您可能感兴趣的文章:
随机阅读: