问题描述
考虑这个名单,其中,串>
List<string> data = new List<string>();
data.Add("Text1");
data.Add("Text2");
data.Add("Text3");
data.Add("Text4");
我的问题是:我怎么能得到列表的子集的每个组合?有点像这样的:
The problem I had was: how can I get every combination of a subset of the list?Kinda like this:
#Subset Dimension 4
Text1;Text2;Text3;Text4
#Subset Dimension 3
Text1;Text2;Text3;
Text1;Text2;Text4;
Text1;Text3;Text4;
Text2;Text3;Text4;
#Subset Dimension 2
Text1;Text2;
Text1;Text3;
Text1;Text4;
Text2;Text3;
Text2;Text4;
#Subset Dimension 1
Text1;
Text2;
Text3;
Text4;
我想出了一个体面的解决方案,其中,认为值得在这里分享。
I came up with a decent solution which a think is worth to share here.
推荐答案
我认为,在这个问题的答案,需要一些性能测试。我给它一展身手。它的社区维基的,可随时更新它。
I think, the answers in this question need some performance tests. I'll give it a go. It is community wiki, feel free to update it.
void PerfTest()
{
var list = Enumerable.Range(0, 21).ToList();
var t1 = GetDurationInMs(list.SubSets_LB);
var t2 = GetDurationInMs(list.SubSets_Jodrell2);
var t3 = GetDurationInMs(() => list.CalcCombinations(20));
Console.WriteLine("{0}\n{1}\n{2}", t1, t2, t3);
}
long GetDurationInMs(Func<IEnumerable<IEnumerable<int>>> fxn)
{
fxn(); //JIT???
var count = 0;
var sw = Stopwatch.StartNew();
foreach (var ss in fxn())
{
count = ss.Sum();
}
return sw.ElapsedMilliseconds;
}
OUTPUT:
OUTPUT:
1281
1604 (_Jodrell not _Jodrell2)
6817
Jodrell的更新
我已经建立在发行模式下,即优化。当我通过Visual Studio中运行我没有得到1或2之间一致的偏见,但经过反复运行LB的回答胜利,我得到的答案接近类似,
I've built in release mode, i.e. optimizations on. When I run via Visual Studio I don't get a consistent bias between 1 or 2, but after repeated runs LB's answer wins, I get answers approaching something like,
1190
1260
more
但如果我在命令行中运行测试,而不是通过Visual Studio中,我得到的结果更是这样
but if I run the test harness from the command line, not via Visual Studio, I get results more like this
987
879
still more
这篇关于我怎样才能得到一个子集的所有可能的组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!