HackerRank Diagonal Difference Problem Solution
HackerRank Diagonal Difference Problem Solution
123 Search
456
9 8 9
The left-to-right diagonal = 1+5+9 = 15. The right to left diagonal = 3+5+9=17. Their
absolute difference is |15-17| = 2.
Function description
Subscribe To Channel
Return
Constraints
Output Format
Return the absolute difference between the sums of the matrix's two diagonals as a
single integer.
#!/bin/python3
import math
import os
import random
import re
import sys
Crafted with by TemplatesYard | Distributed by Blogger
#
CLOSE ADS CLOSE ADS
# Complete the 'diagonalDifference' function below.
#
# The function is expected to return an INTEGER.
# The function accepts 2D_INTEGER_ARRAY arr as parameter.
#
def diagonalDifference(arr):
temp = 0
emp = 0
for i in range(0,len(arr)):
temp = temp + arr[i][i]
for j in range(0,len(arr)):
emp = emp + arr[j][len(arr)-1-j]
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
arr = []
for _ in range(n):
arr.append(list(map(int, input().rstrip().split())))
result = diagonalDifference(arr)
fptr.write(str(result) + '\n')
fptr.close()
CLOSE ADS CLOSE ADS
Problem solution in Java Programming.
Code
import java.util.Scanner;
int main() {
/* Enter your code here. Read input from STDIN. Print output
to STDOUT */
int matrix[100][100];
int i;
cin>>i;
for(int x=0;x<i;x++){
for(int y=0;y<i;y++){
cin>>matrix[x][y];
}
}
i di 1 di 2
int diag1,diag2;
diag1=0;diag2=0;
for(int
CLOSE ADS x=0;x<i;x++) CLOSE ADS
{
diag1=diag1+matrix[x][x];
}
for(int x=i-1;x>-1;x--)
{
diag2=(diag2+matrix[i-x-1][x]);
}
int diff = diag1-diag2;
if(diff<0){
cout<<-(diff);
}
else
cout<<diff;
return 0;
}
int main() {
int n,a[100][100],i,j,d1=0,d2=0,dif;
scanf("%d",&n);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
if(i==j)
d1=d1+a[i][j];
if(i==(n-j-1))
d2=d2+a[i][j];
}
}
dif=abs(d1-d2);
printf("%d",dif);
return 0;
}
CLOSE ADS CLOSE ADS
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});
Facebook Twitter
Posted by: YASH PAL
Yash is a Full Stack web developer. he always will to help others. and this approach