c# - C#中的组合算法

标签 c# algorithm combinations

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

示例:

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

A != null and B != null
A != null and B == null
A == null and B != null
A == null and B == null

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

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

我不知道这个组合叫什么,所以我怎么能在字段数是变量的代码中做到这一点?

谢谢!

最佳答案

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

   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,输出是

  A != null and B != null
  A == null and B != null
  A != null and B == null
  A == null and B == null

编辑:一个小的修改让您可以输入自己的名字:

  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));

关于c# - C#中的组合算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35745040/

相关文章:

c# - 当 Gacutil.exe 拒绝服务时如何从 GAC 中删除 dll

c# - asp.net弹出确认窗口

python - 如何优化解决方案以避免超出内存限制错误或什么可能让我出错?

`otherwise` 函数中的 Haskell 非详尽模式

php - 如何在 PHP 中生成字符串的所有排列?

c# - JSON.Net 将结构序列化/反序列化为字符串

c# - 带有 ProtoBuf.net 的通用序列化器

c++ - 如果一个数字小于 "Max"数组中的相应数字,如何将其添加到数组中?

algorithm - 倒置的预期次数--来自Cormen的算法导论

c# - 获取字符串数组的连续元素的所有组合,同时保留剩余元素 C#