2014-11-05 99 views
0

嘿傢伙我想打它檢查一個二維數組是否是對角佔優的函數或不如何檢查是否一個二維數組是對角佔優Java中

任何想法?

我已經設法找到diagonall,但如何檢查對角支配?

public static int arraySum(int[][] array){ 
    int total = 0; 

    for (int row = 0; row < array.length; row++) 
    { 

     total += array[row][row]; 
    } 

    return total; 
} 
+0

添加了其它的值,看看是否對角線值比其他值總和 – 2014-11-05 19:08:49

+0

以及我怎樣做大不計算對角線上的已有值,將其他值相加 – 2014-11-05 19:12:32

+0

@KostasMatrix看到我的答案,它完成了這一點。 – APerson 2014-11-05 19:13:29

回答

2

根據Wikipedia,一個對角佔優矩陣是這樣的:

爲矩陣的每一行,行中的對角元素的幅值大於或等於所有其它的量值的總和(非對角線)在那一行中。

這只是檢查弱對角優勢,給出一個二維數組:

public boolean isDiagonallyDominant(int[][] array) { 
    int otherTotal = 0; 

    // Loop through every row in the array 
    for(int row = 0; row < array.length; row++) { 
     otherTotal = 0; 

     // Loop through every element in the row 
     for(int column = 0; column < array[row].length; column++) { 

      // If this element is NOT on the diagonal 
      if(column != row) { 

       // Add it to the running total 
       otherTotal += Math.abs(array[row][column]); 
      } 
     } 

     // If this diagonal element is LESS than the sum of the other ones... 
     if(Math.abs(array[row][row]) < otherTotal) { 

      // then the array isn't diagonally dominant and we can return. 
      return false; 
     } 
    } 
    return true; 
} 
+0

@ Turing85固定。 – APerson 2014-11-05 19:16:51

+0

你必須使用if-clause中的絕對值...... – Turing85 2014-11-05 19:17:44

+0

@ Turing85固定。謝謝你發現! – APerson 2014-11-05 19:18:45

2

從理論上講:第i行中,檢查第i個項目低於該行的其他值的絕對值之和的情況:

public boolean checkDominance(int[][] matrix) 
{ 
    for (int i = 0; i < matrix.length; ++i) 
    { 
     int diagEl = Math.abs(matrix[i][i]); 
     int sum = 0; 
     for (int j = 0; j < matrix[0].lenght; ++j) 
     { 
      if (i == j) { continue; } 
      sum += Math.abs(matrix[i][j]); 
     } 
     if (sum > diagEl) { return (false); } 
    } 
    return (true); 
} 
相關問題