簡體   English   中英

C#中的組合算法

[英]Combination Algorithm in C#

我需要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));

在這種情況下,我通常堅持簡單的遞歸,因為它很容易理解。 沒有解釋,我只是讓(未經測試的)代碼自己說話:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM