Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...