2014-10-02 179 views
0

我有一些矩陣元素比較的問題。下面是代碼:矩陣元素比較

int coll = 0; 
for (int i = 0; i < 9; i++) 
{ 
    for (int j = 0; j < 9; j++) 
    { 
     int tmp = 0; 
     for (int k = 0; k < 9; k++) 
     { 
      if (matrix[i, j] == matrix[i, k]) 
      { 
       tmp++; 
       Console.WriteLine("{0},{1} coll {2},{3}-al", i, j, i, k); 
      } 
      coll += tmp; 
     } 

    } 
} 

的代碼要稱爲一個matrix數組的元素進行比較。當列中的2個元素相同時,我將增加tmp值。在末尾coll將增加陣列實際元素的碰撞次數。問題在於程序只能找到元素與自身的碰撞。例如,對於像

1234 
1342 
2341 
2413 

0:0位置將只與自身碰撞而不與1:0碰撞。誰能告訴我爲什麼?

+0

矩陣的請告訴我定義?矩陣是9x9?在數獨求解器上工作? – 2014-10-02 09:04:55

+0

'矩陣'的類型是什麼?它是'int [,]'還是object [,]'? – Henrik 2014-10-02 09:04:59

+0

將'coll + = tmp;'移到內循環之外。 – ja72 2014-10-02 12:36:56

回答

0

嘗試這個邏輯:

class Program 
{ 
    static void Main(string[] args) 
    { 
     int[,] matrix=new int[,] { 
      { 1, 2, 3, 4 }, 
      { 1, 3, 4, 2 }, 
      { 2, 3, 4, 1 }, 
      { 2, 4, 1, 3 } }; 

     // This returns the #of collisions in each column 
     Debug.WriteLine(CheckColumn(matrix, 0)); // 2 
     Debug.WriteLine(CheckColumn(matrix, 1)); // 1 
     Debug.WriteLine(CheckColumn(matrix, 2)); // 1 
     Debug.WriteLine(CheckColumn(matrix, 3)); // 0 
    } 

    static int CheckColumn(int[,] matrix, int column) 
    { 
     int[] data=new int[matrix.GetLength(0)]; 
     for(int i=0; i<data.Length; i++) 
     { 
      data[i]=matrix[i, column]; 
     } 
     var hist=data.GroupBy(i => i) 
      .OrderByDescending(g => g.Count()) 
      .Select(g => new { Num=g.Key, Dupes=g.Count()-1 }) 
      .Where(h=>h.Dupes>0); 

     return hist.Count()>0?hist.Sum(h=>h.Dupes):0; 
    } 
} 

我使用的代碼從https://stackoverflow.com/a/10335326/380384

+0

感謝您的回覆很快我會試試:) – 2014-10-03 10:01:24