2016-01-24 65 views
0

我正在尋找從長度爲k的int數組中獲取所有可能的長度爲n的int數組的最佳方法,其中包含n-1個項目爲null的選項。 例如我有5個單元(k = 5)的陣列和我想的3的所有組合(N = 3)的長度3的從長度爲k的數組獲得n上的所有組

int[] numbers = new int[5] {1, 2, 3, 4, 5}; 

和可能的子陣列:

{1, null,null},{1,null,2},{1,2,null} .....等等。

什麼是最好的方法來做到這一點? Matan

+0

我目前對此毫無頭緒,試圖從互聯網上獲取有關處理該問題的最佳方法的信息。我發現了一些很好的算法,但它不包含無效的可能性。 –

+0

看看這個解決方案:http://stackoverflow.com/a/10630026。它會給你所有的排列,沒有null值。在這個例子中,將'Enumerable.Range(1,3)'替換爲你的'numbers'變量。 – Serge

+0

謝謝,這很好,但我的空選項需要在我的需要 –

回答

0

您可以在您的numbers數組中包含null。 該代碼產生除{null,null,null}之外的所有可能的排列。

var numbers = new int?[]{null, 1, 2, 3, 4, 5}; 
var result = new List<int?[]>(); 

foreach (int? x in numbers) 
{ 
    foreach (int? y in numbers) 
    { 
     foreach (int? z in numbers) 
     { 
      if (x == null && y == null && z == null) 
       continue; 

      result.Add(new int?[] { x, y, z }); 
      Console.WriteLine("x: {0} - y: {1} - z: {2}", x, y, z); 
     } 
    } 
} 
+0

似乎不錯,我會試試看 –

相關問題