简体   繁体   中英

Combination Algorithm in C#

I need a combination of n fields where each field can be equal to null or not null. For each combination, the fields cannot be repeated. Basically, there should be a total of 2^n combinations.

Example:

if I have 2 fields A and B , the combinations in the output should be:

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

if I have 3 fields A, B, and C, the combinations in the output should be:

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

I don't know what this combination is called, so how can I do this in code where the number of fields is a variable?

Thanks!

If you want a generator of such lines you can use 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));

For count = 2 the output is

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

Edit: A small modification lets you put your own names:

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

I usually stick to simple recursion in cases like this, because it's so easy to understand. No explanation, I'll just let the (untested) code talk for itself:

public void Generate()
{
    Create("", 0);
}

private string[] names = new[]{ "A", "B", "C" };

public void Create(string s, int current)
{
    if (current != 0)
    { 
        s += " and ";
    }

    if (current != names.Length)
    {
        string c1 = s + names[current] + " == null"; // case 1
        string c2 = s + names[current] + " != null"; // case 2

        Create(c1, current+1);
        Create(c2, current+1);
    }
    else
    {
        Console.WriteLine(s);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM