![](/img/trans.png)
[英]You are given a square matrix of size N times N. Calculate the absolute difference of the sums across the two main diagonals
[英]Difference diagonals
我試圖讓這個 function 接收一個包含 N 行和 N 列的數組,其中將主對角線的值和次對角線的值相加,最后,function 計算這些數字的差異。 但是,在計算次對角線時,例如在 3x3 數組中計算 position [1][1] 時,它不會求和,就好像 function 忽略了強加於 else if 的業務規則。
我的代碼
function diagonalDifference (arr){
let n = arr.length;
let diagonPrim = 0;
let diagonSec = 0;
for(let i = 0; i < n; i++){
for(let j = 0; j < n; j++){
if (i == j){
diagonPrim += arr[i][j];
console.log(i, j);
console.log(diagonPrim);
} else if (i == j || i + j == n - 1){
diagonSec += arr[i][j];
console.log(i, j);
console.log(diagonSec);
};
};
};
let sum = diagonPrim - diagonSec;
return sum;
}
觀察。 我將 consoles.log 放在 if 中,以了解我是否在跳過數組中的位置。
例子:
輸入:
10, 2, 3,
4, 52, 6,
11, 8, 52,
Output 預期:
48
我的 output:
100
你能幫我弄清楚為什么這個 position 不計算嗎?
這是因為您有一個if-else
語句。 如果第一個條件執行,則第二個條件不會執行,即使它的條件為真。 因此,中間元素將僅計入主要對角線,而不是次要對角線。
此外,正如 chazsolo 評論的那樣,您在輔助對角線檢查中有一個不必要的條件 ( i == j
)。 i + j === n - 1
是檢查次對角線的充分條件。
試試這樣:
function diagonalDifference (arr){
let n = arr.length;
let diagonPrim = 0;
let diagonSec = 0;
for(let i = 0; i < n; i++){
for(let j = 0; j < n; j++){
if (i === j){
diagonPrim += arr[i][j];
}
if (i + j === n - 1){
diagonSec += arr[i][j];
};
};
};
let sum = diagonPrim - diagonSec;
return sum;
}
編輯:但是,即使正確,這仍然不是解決此問題的有效方法。 如果性能很重要,您可以通過直接在對角線上循環來解決問題,而無需檢查所有n 2 個元素,請參閱 wLui155 的評論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.