如何获得一个arraylist的所有组合? [英] how to get all combination of an arraylist?
本文介绍了如何获得一个arraylist的所有组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串数组列表abcde"我想要一种方法来返回另一个数组列表,其中包含 C# 中给定数组列表(例如:ab、ac、ad...)的所有可能组合
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)
推荐答案
关于需要长度为 2 的组合的评论:
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);
}
响应您的任何长度的
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屋!
查看全文