如何获得子集的所有可能组合? [英] How can I obtain all the possible combination of a subset?

查看:38
本文介绍了如何获得子集的所有可能组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个List

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

输出:

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

这篇关于如何获得子集的所有可能组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆