HackerRank Diagonal Difference Problem Solution
In this post, We are going to solve HackerRank Diagonal Difference Problem.
Given a square matrix, calculate the absolute difference between the sums of its diagonals.
For example, the square matrix arr 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 diagonal difference 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 matrix’s 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
Diagonal Difference C Solution
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int n;
scanf("%d", &n);
int TlBr = 0;
int TrBl = 0;
int i,j;
int d;
for (i=0; i<n; i++) {
for (j=0; j<n; j++) {
scanf("%d", &d);
if (i==j) TlBr += d;
if ((i+j)==(n-1)) TrBl +=d;
}
}
int sum = TlBr - TrBl;
printf("%d", abs(sum));
return 0;
}
Diagonal Difference C++ Solution
#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;
int arr[100][100] = {};
cin >> n;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin >> arr[i][j];
}
}
int sumA=0,sumB=0;
for(int i=0;i<n;i++){
sumA+=arr[i][i];
sumB+=arr[n-i-1][i];
}
cout << abs(sumA-sumB) << endl;
return 0;
}
Diagonal Difference C Sharp Solution
using System;
using System.Collections.Generic;
using System.IO;
class Solution {
static void Main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
int t = Convert.ToInt32(Console.ReadLine());
//var matrixList = new List<int[]>();
var difference = SumOfDifference(t);
Console.WriteLine(difference);
}
private static int SumOfDifference(int t)
{
int diagonal1Sum = 0;
int diagonal2Sum = 0;
for (int i = 0; i < t; i++)
{
// read next line
var elements = Console.ReadLine();
var splitElements = elements.Split(' ');
var row = Array.ConvertAll(splitElements, Convert.ToInt32);
diagonal1Sum += row[i];
diagonal2Sum += row[t - i - 1];
}
int difference = Math.Abs(diagonal1Sum - diagonal2Sum);
return difference;
}
}
Diagonal Difference Java Solution
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
/*
* Complete the 'diagonalDifference' function below.
*
* The function is expected to return an INTEGER.
* The function accepts 2D_INTEGER_ARRAY arr as parameter.
*/
public static int diagonalDifference(List<List<Integer>> arr) {
// Write your code here
int sum1 = 0;
for(int i = 0; i < arr.size(); i++) {
sum1 += arr.get(i).get(i);
}
int sum2 = 0;
for(int j = 0; j < arr.size(); j++) {
sum2 += arr.get(arr.size()-1-j).get(j);
}
int totalt = sum1-sum2;
if(totalt < 0) {
totalt *= -1;
}
return totalt;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int n = Integer.parseInt(bufferedReader.readLine().trim());
List<List<Integer>> arr = new ArrayList<>();
IntStream.range(0, n).forEach(i -> {
try {
arr.add(
Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
.map(Integer::parseInt)
.collect(toList())
);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
});
int result = Result.diagonalDifference(arr);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}
Diagonal Difference JavaScript Solution
function processData(input) {
var currentLine = 0;
var total = 0;
var leftDiag = 0;
var rightDiag = 0;
inputArray = input.split("\n");
var n = parseInt(inputArray[currentLine].trim(), 10);
var values = inputArray[1].split(' ');
for(var i=0; i<n; i++){
rowValues = inputArray[i+1].split(' ');
leftDiag += parseInt(rowValues[i].trim());
rightDiag += parseInt(rowValues[n-1-i].trim());
}
total = Math.abs(leftDiag-rightDiag);
console.log(total)
}
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 Python Solution
n = int(input())
ar = []
for i in range(n):
ar.append(input().split(" "))
d1 = 0
d2 = 0
for i in range(n):
d1 += int(ar[i][i])
d2 += int(ar[i][-i-1])
print (abs(d1 - d2))
Other Solutions
You have made some really good points there. I checked on the internet for more info about the issue and found most people will go along with your views on this site.
Aw, this was an incredibly nice post. Taking a few minutes and actual effort to make a very good article… but what can I say… I put things off a lot and never seem to get nearly anything done.
Greetings! Very useful advice in this particular article! It is the little changes which will make the biggest changes. Many thanks for sharing!
This blog was… how do I say it? Relevant!! Finally I’ve found something that helped me. Thanks a lot.
You should take part in a contest for one of the finest websites online. I’m going to recommend this blog!
Nice post. I learn something new and challenging on websites I stumbleupon every day. It will always be helpful to read content from other authors and practice a little something from other sites.
I used to be able to find good advice from your blog posts.