-
Notifications
You must be signed in to change notification settings - Fork 1
/
diagonaldefrence.js
49 lines (34 loc) · 1.15 KB
/
diagonaldefrence.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Given a square matrix, calculate the absolute difference between the sums of its diagonals.
// For example, the square matrix is shown below:
// 1 2 3
// 4 5 6
// 9 8 9
// The left-to-right diagonal = . The right to left diagonal = . Their absolute difference is .
// Function description
// Complete the function in the editor below.
// diagonalDifference takes the following parameter:
// int arr[n][m]: an array of integers
// Return
// int: the absolute diagonal difference
// Input Format
// The first line contains a single integer, , the number of rows and columns in the square matrix .
// Each of the next lines describes a row, , and consists of space-separated integers .
// Constraints
// Output Format
// Return the absolute difference between the sums of the matrix's two diagonals as a single integer.
// Sample Input
// 3
// 11 2 4
// 4 5 6
// 10 8 -12
// Sample Output
function diagonalDifference(arr)
{
let leftToRight = 0;
let rightToLeft = 0;
for (let i = 0; i < arr.length; i++) {
leftToRight += arr[i][i];
rightToLeft += arr[i][arr.length - 1 - i];
}
return Math.abs(leftToRight - rightToLeft);
}