首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C#中的组合算法

C#中的组合算法
EN

Stack Overflow用户
提问于 2016-03-02 10:49:15
回答 2查看 298关注 0票数 1

我需要n个字段的组合,其中每个字段可以等于null或null。对于每个组合,都不能重复字段。基本上,应该有2^n的组合。

示例:

如果我有两个字段AB,那么输出中的组合应该是:

代码语言:javascript
运行
复制
A != null and B != null
A != null and B == null
A == null and B != null
A == null and B == null

如果我有3个字段A、B和C,那么输出中的组合应该是:

代码语言:javascript
运行
复制
A != null and B != null and C != null
A != null and B != null and C == null
A != null and B == null and C != null
A != null and B == null and C == null
A == null and B != null and C != null
A == null and B != null and C == null
A == null and B == null and C != null
A == null and B == null and C == null

我不知道这个组合的名称是什么,那么如何在字段数是一个变量的代码中这样做呢?

谢谢!

EN

Stack Overflow用户

回答已采纳

发布于 2016-03-02 11:04:05

如果您想要这样的行生成器,可以使用Linq。

代码语言:javascript
运行
复制
   int count = 2;

   var lines = Enumerable
     .Range(0, 1 << count) // 1 << count == 2 ** count
     .Select(item => String.Join(" and ", Enumerable
       .Range(0, count)
       .Select(index => ((Char) ('A' + index)).ToString() + 
                        ((item >> index) % 2 == 0 ? " != null" : " == null"))));


   // Let's print out all the lines generated
   Console.Write(String.Join(Environment.NewLine, lines));

对于count = 2,输出是

代码语言:javascript
运行
复制
  A != null and B != null
  A == null and B != null
  A != null and B == null
  A == null and B == null

编辑:一个小小的修改可以让你把你自己的名字:

代码语言:javascript
运行
复制
  String[] names = new String[] { "A", "B", "C" };

  var lines = Enumerable
    .Range(0, 1 << names.Length) // 1 << count == 2 ** count
    .Select(item => String.Join(" and ", Enumerable
       .Range(0, names.Length)
       .Select(index => names[index] +
                        ((item >> index) % 2 == 0 ? " != null" : " == null"))));

  // Let's print out all the lines generated
  Console.Write(String.Join(Environment.NewLine, lines));
票数 3
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35745040

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档