2013-09-05 17 views
2

我需要找到工作原理是這樣的函數:一定量的數字之間的所有可能的組合的C#

int[] matches = getAllPossibleCombinations(
    int lengthOfEachIntReturnedInArray, 
    List<char> typesOfElementsUsedInCombinations); 

輸入元件將這些(這只是一個例子):

  • int lengthofeachintreturnedinarray = (int) 2
  • List<char> typesofelementsusedincombinations = {a,b}

然後輸出將呈現T Ó是(在一個字符串數組):

AA

AB

BA

BB

陣列中的每個單獨的輸出元件必須具有由下式定義的長度方法中的第一個參數(在本例中爲2),並且必須包含第二個參數中給定字母之間的所有可能組合

我已經看到關於powersets的一些東西,我應該使用它們,還是應該使用foreach循環來適應這項工作?

!提出的問題與上面的答案是不一樣的,它不使用set lenghts!

+0

你有這樣做的 – Adrian

+0

債券原子(化學)有什麼要求 – user2606722

+1

你想要的第二個參數是一個'名單'或'列表'?即每個單獨的元素可以多於一個字符? –

回答

3

我會帶你到Eric Lippert的article在Linq實施Cartesian Product,他寫爲extension method

static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) 
{ 
    IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; 
    return sequences.Aggregate( 
    emptyProduct, 
    (accumulator, sequence) => 
     from accseq in accumulator 
     from item in sequence 
     select accseq.Concat(new[] {item})); 
} 

利用這一點,你可以實現你的方法是這樣的:

static IEnumerable<string> GetAllPossibleCombinations(
    int lengthofeachintreturnedinarray, 
    IEnumerable<string> typesofelementsusedincombinations) 
{ 
    return Enumerable 
     .Repeat(typesofelementsusedincombinations, lengthofeachintreturnedinarray) 
     .CartesianProduct() 
     .Select(strings => String.Concat(strings)); 
} 
+0

這將完全返回上面提到的值? – user2606722

+1

@ user2698666是的,它會的。 –

+0

我試過了代碼,但它在第二塊代碼中的.CartesianProduct()行中引發錯誤:「Error 1」System.Collections.Generic.IEnumerable >'不包含'CartesianProduct'的定義並且沒有擴展方法'CartesianProduct'接受類型'System.Collections.Generic.IEnumerable 的第一個參數''可以找到「我該如何解決這個問題? – user2606722

相關問題