2016-03-02 43 views
1

我需要組合n字段,其​​中每個字段可以等於null或非null。對於每個組合,這些字段不能重複。基本上,應該有總共2^n的組合。C#中的組合算法

實施例:

如果我有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 

我不知道這個組合被稱爲,所以我怎麼能做到這一點我n代碼字段的數量是一個變量?

謝謝!

+3

計數二進制? –

+0

如果您認爲'!= null'的意思是「存在於子集中」而== null意味着「子集中不存在」,則這是「{A,B,C}」的冪集。 –

+0

我沒有得到你所需要的,你需要用於生成所有這些可能性的算法?另一件事是你把這些回報放在哪裏? –

回答

3

如果你想有一個發電機,線路可以使用的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)); 
+0

謝謝,但我使用的領域是變量..他們不是字面上「A」,「B」或「C」.. – pineapple

+0

@保羅阿德里安佩納:一個小修改(見我的編輯),讓你提供自己的名字 –

+0

我想我明白了..非常感謝..這是輝煌! – pineapple

0

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

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