HackerRank Diagonal Difference Solution

Hello Programmers, In this post, you will know how to solve the HackerRank Diagonal Difference Solution. This problem is a part of the HackerRank Algorithms Series.

Ezoicreport this adHackerRank Diagonal Difference Solution
HackerRank Diagonal Difference Solutions

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.

HackerRank Diagonal Difference Solution

Ezoicreport this adProblem

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 = 1 + 5 +9 = 15. The right to left diagonal = 3 + 5 + 9 = 17. Their absolute difference is |15 – 17| = 2.

Function description

Complete the DiagonalDifference 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, n, the number of rows and columns in the square matrix arr.
Each of the next n lines describes a row, arr[i], and consists of n space-separated integers arr[i][j].

Constraints

-100 <= arr[i][j] <= 100

Output Format

Return the absolute difference between the sums of the matrixs two diagonals as a single integer.

Sample Input

3
11 2 4
4 5 6
10 8 -12

Sample Output

15

Explanation

The primary diagonal is:

11
5
-12

Sum across the primary diagonal: 11 + 5 12 = 4

The secondary diagonal is:

4

5
10

Sum across the secondary diagonal: 4 + 5 + 10 = 19
Difference: |4 – 19| = 15

Note: |x| is the absolute value of x

HackerRank Diagonal Difference Solution

Diagonal Difference Solution in C

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */    
    int N , a[100][100];
    scanf("%d",&N);
    int i,j,d1=0,d2=0;
    for(i=0;i<N;i++)
        for(j=0;j<N;j++)
        scanf("%d",&a[i][j]);
    for(i=0;i<N;i++)
        { 
      d1+=a[i][i];
        d2+=a[i][N-1-i];
       
    }
    int b=abs(d1-d2);
    printf("%d",b);
        
        
    
    return 0;
}

Diagonal Difference Solution in Cpp

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    int N; 
    cin >> N; 
    
    int i, j; 
    
    int sumdiag1 = 0; 
    int sumdiag2 = 0; 
    for(i = 0; i < N; i++){
        for(j = 0; j< N; j++)
        {
           int no; 
           cin >> no; 
           if(i == j)
               sumdiag1 += no; 
           if(i+j == N-1)
              sumdiag2 += no; 
        }
    }
    
    cout << abs(sumdiag1 - sumdiag2);
    return 0;
}

Diagonal Difference Solution in Java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        int n;
        Scanner in=new Scanner(System.in);
        n=in.nextInt();
        int a[][]=new int[n][n];
        for(int i=0;i<n;i++){
        	for(int j=0;j<n;j++){
        		a[i][j]=in.nextInt();
        	}
        }
        int pd=0,npd=0;
        for(int i=0;i<n;i++){
        	for(int j=0;j<n;j++){
        		if(j==i)
        			pd=pd+a[i][j];
        	}
        }
        for(int i=0;i<n;i++){
        	for(int j=0;j<n;j++){
        		if(i==n-j-1){
        			npd=npd+a[i][j];
        		}
        	}
        }
        int dif=npd-pd;
        dif=Math.abs(dif);
        System.out.println(dif);
    }
}
Ezoicreport this ad

Diagonal Difference Solution in Python

n = input()
arr=[]
for _ in range(n):
    temp = map(int,raw_input().split())
    arr.append(temp)
s1,s2 = 0,0
for i in range(n):
    s1 += arr[i][i]
    s2 += arr[-i-1][i]
print abs(s1-s2)

Diagonal Difference Solution using JavaScript

function processData(input) {
    var lines = input.split("\n");
    var N = parseInt(lines[0]);
    var t = 0;
    for(i = 1; i <= N; i++) {
        var line = lines[i].split(" ");
        t += parseInt(line[i - 1]) - parseInt(line[N - i]);
    }
    console.log(Math.abs(t));
} 
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});
process.stdin.on("end", function () {
   processData(_input);
});

Diagonal Difference Solution in Scala

import scala.io._
object Solution {
def main(args: Array[String]) = {
    val size = StdIn.readInt()
    var lr: Int = 0
    var rl: Int = 0
    for(i <- 0 to (size - 1)) {
      val rowStr = StdIn.readLine().split(" ")
      lr += Integer.parseInt(rowStr(i))
      rl += Integer.parseInt(rowStr(size - i - 1))
    }
    println(Math.abs(lr - rl))
  }
}

Diagonal Difference Solution in Pascal

Const tfi='';
      tfo='';
Var   n:longint;
Procedure process;
    Var i,j,x,mid1,mid2:longint;
    Begin
        Read(n);
        mid1:=0;
        mid2:=0;
        For i:=1 to n do
            For j:=1 to n do
                Begin
                    Read(x);
                    If i-j=0 then inc(mid1,x);
                    If i+j=n+1 then inc(mid2,x);
                End;
        Write(abs(mid1-mid2));
    End;
BEGIN
    Assign(input,tfi); Reset(input);
    Assign(output,tfo); Rewrite(output);
        process;
    Close(input); Close(output);
END.

Disclaimer: This problem (Diagonal Difference) is generated by HackerRank but the Solution is Provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.

Next: HackerRank A Very Big Sum solution

Sharing Is Caring

Leave a Comment

Ezoicreport this ad